Djony
Djony

Reputation: 181

getServerSideProps external api data fetching returns error

My http axios api data fetch attempt inside the getServerSideProps function always returns error. I am succcessfully recovering token and userId from cockies, and trying to pass them as parameters to make server api call.

export const getServerSideProps: GetServerSideProps = async (ctx) => {

        try {
        const { userId, token } = ctx.req.cookies; 
        // console.log(userId)      
        // console.log(token)               
           
            const res = await api.get(`/users/show/${userId}`, {
              headers: { token },
         
            })
          console.log(res.data)
            const userData  = res.data;      

          if (!userData) {
            return {
              notFound: true,
            }
          }
          
            return {
              props: {  
                userData
         
              }
            }
          
        } catch (error) {
          return error
        }
          
          
      }

And keep getting same error:

  Server Error
Error: Additional keys were returned from `getServerSideProps`. Properties intended for your component must be nested under the `props` key, e.g.:

    return { props: { title: 'My Title', content: '...' } }

Keys that need to be moved: config, request, response, isAxiosError, toJSON.

Upvotes: 0

Views: 864

Answers (1)

Chemi Adel
Chemi Adel

Reputation: 2165

The returned object should always be on way

return { props: {//add your object here} }

export const getServerSideProps: GetServerSideProps = async (ctx) => {

        try {
        const { userId, token } = ctx.req.cookies; 
        // console.log(userId)      
        // console.log(token)               
           
            const res = await api.get(`/users/show/${userId}`, {
              headers: { token },
         
            })
          console.log(res.data)
            const userData  = res.data;      

          if (!userData) {
            return {
              return { props: { notFound: true } },
            }
          }
          
            return {
              props: {  
                userData
         
              }
            }
          
        } catch (error) {
          return { props: {} }
        }
          
          
      }

Upvotes: 1

Related Questions