Search code examples
reactjsreact-hooksnext.jsuse-effect

Right way to handle error in getServerSideProps in Nextjs


I am trying to handle any errors that come through getServerSideProps, which I check in via the if else condition, that works fine until I have any other hooks called like useEffect. When I use the hook useEffect it gives the following error - which is though correct as per hook rules.

But it gives error Error: React Hook "useEffect" is called conditionally. React Hooks must be called in the exact same order in every component render, when I use useEffect hook and do npm run build.

Can someone please help me, how to handle this



function Test({ data }) {
    console.log(data)

    if (data?.err) {
         return (<Error statusCode={data.err} />)
     }

 useEffect(() => {
   //fetch any data or do something

    return () => {
      
    };
  }, []);
  

return(<div>Return Div</>)

}

export default Test


export const getServerSideProps = async (context) => {


  const { data } = await axios.get(`${baseUrl}HomePage/all`).catch(err => {
    const dataerr = { data: { err: `${JSON.stringify(err?.response?.status)}` } }

    return dataerr
  })

  console.log(data)
  return { props: { data } }

}



Solution

  • You are using a conditional early return in Test. Move the useEffect (and all other hooks) hook above any function component returns so it is (they are) called unconditionally each render cycle.

    function Test({ data }) {
      console.log(data);
    
      useEffect(() => {
        //fetch any data or do something
    
        return () => {
          
        };
      }, []);
    
      if (data?.err) {
        return <Error statusCode={data.err} />'
      }
    
      return <div>Return Div</>;
    }