Rahele Nazari
Rahele Nazari

Reputation: 401

layout component does not unmount on server side when children unmounted

I use next.js. In my index route, according to "step" State, I render some component which has own Layout, when the last condition is true, "FormContainer" without any Layout suppose to render but it renders into the previous Layout only when the page gets a refresh. do you have any idea what happened?


const Home = () => {
  const token = cookies.get('accessToken');
  const [step, setStep] = useState('');
  const [onBoarding, setOnBoarding] = useState(data);


  const render = () => {
    switch (step) {
      case 'otp':
        return (
          <Otp
            submitOtp={submitOtp}
            changeMobile={changeMobile}
            changeOTP={changeOtp}
            handleOtpChange={handleOtpChange}
            otp={otp}
          />
        );
      case 'NationalId':
        return <NationalId submitNationalId={submitNationalId} />;
      default:
        return <Mobile submitMobile={submitMobile} />;
    }
  };

  return token && onBoarding ? (
    <FormContainer data={onBoarding} nationalId={nationalId}/>
  ) : (
    <Layout>{render()}</Layout>
  );
};

export default Home;

Upvotes: 3

Views: 461

Answers (1)

Afsanefda
Afsanefda

Reputation: 3339

This is mainly because your condition is not identified on SSR! you have to check the condition in getInitialProps and pass it as a prop:

const Home = ({condition}) => {
  const token = cookies.get('accessToken');
  const [step, setStep] = useState('');
  const [onBoarding, setOnBoarding] = useState(data);

  const render = () => {
    switch (step) {
      case 'otp':
        return (
          <Otp
            submitOtp={submitOtp}
            changeMobile={changeMobile}
            changeOTP={changeOtp}
            handleOtpChange={handleOtpChange}
            otp={otp}
          />
        );
      case 'NationalId':
        return <NationalId submitNationalId={submitNationalId} />;
      default:
        return <Mobile submitMobile={submitMobile} />;
    }
  };

  return condition ? (
          <FormContainer data={onBoarding} nationalId={nationalId} />
       ) : (
          <Layout>{render()}</Layout>
   );

Home.getInitialProps = async ({ req, store }) => {
  const cookies = new Cookies(req.headers.cookie);
  const token = cookies.accessToken;
  const data = store.getState(
    state => state.onBoarding.data, //if it is from store or api call
  );
  const condition = !!(token && data);
  return { condition };
};

export default Home;

in this way, your condition is known both client and server-side!

Upvotes: 3

Related Questions