Search code examples
javascriptreactjsnext.jsreact-context

How to get state value into getServerSideProps to use for an API call


I currently have a context with the state of name, I currently need to get the state to use it in an API call reliant on it.

age.js

import { useStateContext } from "@/context/StateContext";
import axios from "axios";

export default function Age({data}) {
    let {name} = useStateContext();

    return (
        <div>
            Your name is {name}
            Your age is {data.age}
        </div>
    );
}

export async function getServerSideProps({}){

//GET NAME HERE

baseURL = "        "
const data = axios.get(`${baseURL}?name=${name}`)
    return {
        props:{
            data: data
        }
    }
}

and I have a contextProvider like so that is wrapped in the _app.js with a code base like this:

import React, { createContext, useContext, useState, useEffect } from 'react'
const Context = createContext();

export const StateContext = ({children}) => {
    const [name, setName] = useState();
    return (
        <Context.Provider
        value={{ name, setName, }}>
            {children}
        </Context.Provider>
  )
}
export const useStateContext = () => useContext(Context);

I have tried initializing let {name} = useStateContext(); in getServerSideProps, but met with the error of

React Hook "useStateContext" is called in function "getServerSideProps" that is neither a React function component nor a custom React Hook function.

Trying to import Context to use Context.getState() doesn't seem to work either or it might be that I did it incorrectly


Solution

  • I don't think it's possible to pass local context to getServerSideProps in the way you are trying here. There's some nice explanations here and here about how getServerSideProps runs. The upshot is that getServerSideProps is running on the webserver and pushing updates down to the client, so it can't access local code or state.

    The getServerSideProps function is capable of accepting a context which includes the client side request, query params, cookies etc. So the best method avaiable to you would be to include the client name in the request as a query param or cookie or what have you, and then make the request from getServerSideProps like (based on what you have above):

    export async function getServerSideProps(context){
    
    baseURL = "        "
    const data = axios.get(`${baseURL}?name=${context.query.name}`)
        return {
            props:{
                data: data
            }
        }
    }
    

    At the same time, you might want to think about your use case. I don't know what data you need but sending a user's info like name through requests is something you might want to avoid if you can. Ultimately, though, that will be context-dependent.