javascriptreactjsnext.js

next page wrapped in a suspense not working properly


I'm having some issues on production with this code. It's working great locally, but when i try to upload it on Netlify i'm getting this error ⨯ useSearchParams() should be wrapped in a suspense boundary at page "/imoveis". and this bellow is the page in question, any ideia?

"use client";

import React, { Suspense } from "react";
import { imoveis } from "../data/imoveis";
import Link from "next/link";
import { useSearchParams } from "next/navigation";

const ImoveisPage = () => {
  const searchParams = useSearchParams();
  const tipo = searchParams.get("tipo");

  const filteredImoveis = tipo
    ? imoveis.filter((imovel) => imovel.tipo === tipo)
    : [];

  return (
    <div className="bg-gray-400 text-black min-h-screen p-8">
      <h1 className="text-2xl">Resultados da Pesquisa</h1>
      <Suspense fallback={<div>Carregando...</div>}>
        {filteredImoveis.length > 0 ? (
          <ul>
            {filteredImoveis.map((imovel, index) => (
              <li
                key={index}
                className="bg-neutral-200 m-2 text-black p-2 w-96"
              >
                <div>
                  <Link href={imovel.path}>
                    <p>{imovel.title}</p>
                    <p>{imovel.price}</p>
                  </Link>
                </div>
              </li>
            ))}
          </ul>
        ) : (
          <p>Nenhum resultado encontrado.</p>
        )}
      </Suspense>
    </div>
  );
};

export default ImoveisPage;

Solution

  • The useSearchParams has to be called only after the Suspense context, you need a wrapper component that handles the suspense part.

    const ImoveisPageWrapper = () => {
      return (
        <div className="bg-gray-400 text-black min-h-screen p-8">
          <h1 className="text-2xl">Resultados da Pesquisa</h1>
          <Suspense fallback={<div>Carregando...</div>}>
            <ImoveisPage />
          </Suspense>
        </div>
      );
    };
    
    const ImoveisPage = () => {
      const searchParams = useSearchParams();
      const tipo = searchParams.get("tipo");
    
      const filteredImoveis = tipo
        ? imoveis.filter((imovel) => imovel.tipo === tipo)
        : [];
    
      return (
        <>
          {filteredImoveis.length > 0 ? (
            <ul>
              {filteredImoveis.map((imovel, index) => (
                <li key={index} className="bg-neutral-200 m-2 text-black p-2 w-96">
                  <div>
                    <Link href={imovel.path}>
                      <p>{imovel.title}</p>
                      <p>{imovel.price}</p>
                    </Link>
                  </div>
                </li>
              ))}
            </ul>
          ) : (
            <p>Nenhum resultado encontrado.</p>
          )}
        </>
      );
    };