1

I am using getServerSideProps() to fetch data on the server side and then display it to the user:

export const getServerSideProps = async () => {
    // fetch some data...
    if (some_error_condition) {
        return { error: "Something happened" };
    }
    return { props: { num: 123 } };
};


export default function Component({ num, error }) {
    if (error) {
        return <>Error: {error}</>;
    }

    const [num, setNum] = useState(num); // <-- this hook is called conditionally

    return <>...</>;
}

In the React component, some hooks depend on the server-side data. Therefore, I need to display a fallback UI before calling those hooks with data which isn't there.

However, this results in this (comprehensible) error:

Error: React Hook "useState" is called conditionally.

How can I best avoid this in a Next.js / getServerSideProps() environment?

Nils
  • 1,755
  • 3
  • 13
  • 25

1 Answers1

1

You can create a new component and dynamic import it

const SuccessComponent = ({ num }) => {
    const [num, setNum] = useState(num);

    return <>...</>;
}


import dynamic from 'next/dynamic';
const SuccessComponent = dynamic(() => import('SuccessComponent'))
export default function Component({ num, error }) {
    if (error) {
        return <>Error: {error}</>;
    }

    return <SuccessComponent num={num}/>
}
iamhuynq
  • 5,357
  • 1
  • 13
  • 36