const returns Undefined when using the getServerSideProps method of Next.js

Asked

Viewed 88 times

-2

Hello, I am using React with Next.js and using the native Next.js method, getServerSideProps to retrieve browser cookies.

It turns out that the breakdown works for the first const, but not for the last.

export const getServerSideProps: GetServerSideProps = async(ctx) => {
  const { level, currentExperience, challengesCompleted, user, userName, accumulatedExperience} = ctx.req.cookies;
  
  return {
    props: {
      level: Number(level ?? 1),
      currentExperience: Number(currentExperience ?? 0),
      challengesCompleted: Number(challengesCompleted ?? 0),      
      user: user || null,
      userName: userName || null,
      accumulatedExperience: Number(accumulatedExperience ?? 0)
    }
    
  };
}

In the case, level, currentExperience and challengesCompleted are returning me correctly 0. user and username, rightfully null

But accumulatedExperience turning back undefined and this makes the mathematical operations are not performed, because returns me Nan.

Does anyone know what it can be ?

1 answer

0


I personally would not use getServerSideProps for that purpose. See, this function is intended to make the Server Side Rendering (SSR), that is, when you need to process something on the server before rendering the page (e.g., take data from the database). You can use other React strategies to load this information when the component is mounted. An output would be to use Hook useEffect

import {useEffect} from 'react'

const MeuApp = () =>{
  useEffect(()=>{
    //AQUI VC CAPTURA OS COCKIES
    },[]})
}

useEffect runs every time the component is mounted and together with useState, you can store the data to be used in the rest of the code.

  • I ended up solving here still with getServerSideProps, but I will make this change since it does not make much sense to capture cookies using SSR. Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.