Search code examples
javascriptreactjsnext.jsvercel

How do you get rid of useSearchParams() and Suspense deployment error?


I'm getting ⨯ useSearchParams() should be wrapped in a suspense boundary at page "/PaymentPage". Read more: https://nextjs.org/docs/messages/missing-suspense-with-csr-bailout

The problem is I have wrapped everything in Suspense, but I'm still getting this error when trying to deploy my application.

'use client';
import React, { useEffect, useState, Suspense } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import PayPalPaymentButtons from '../ui/PayPalButtons';
import ContactForm from '../ui/contact-form';

const PaymentPage: React.FC = () => {
  const router = useRouter();
  const searchParams = useSearchParams();
  const amount = searchParams ? searchParams.get('amount') : null;

  const [paypalClientId, setPaypalClientId] = useState<string | null>(null);

  useEffect(() => {/*...*/}, []);

  if (!paypalClientId) {
    return <Suspense fallback={<div>Loading...</div>}><div>Loading...</div></Suspense>;
  }

  const handleSuccess = () => {
    // Redirect to success page or perform any other action
    router.push('/');
  };

  const handleError = (error: any) => {
    // Handle error, display message, or retry payment
    console.error('Payment error:', error);
  };

  return (
    <Suspense fallback={<div>Loading...</div>}>
    {/* ... */}
    </Suspense>
  );
};

export default PaymentPage;


Solution

  • Please understand that you have to wrap your hook invocation inside a Suspense boundary. So, instead of using Suspense inside PaymentPage, please use Suspense around it.

        <Suspense fallback={<div>Loading...</div>}>
        <PaymentPage />
        </Suspense>
    

    If PaymentPage is used as a page, use one more level of wrapping:

        <Suspense fallback={<div>Loading...</div>}>
        <PaymentComponent />
        </Suspense>
    
    const PaymentComponent = () => {
      const router = useRouter();
      const searchParams = useSearchParams();
      ....
      
    }