Home > Blockchain >  UseContext Get Data from API Returns null
UseContext Get Data from API Returns null

Time:05-22

I am trying to get data from the user but it always returns null, the problem here that the return function runs first so the getUser is null how can i render the useEffect before it returns the provider ?

Here is my code :

import React, { useState, useEffect } from 'react';
import axios from '../axios'

export const UserContexts = React.createContext();

const UserContext =  ({children}) => {



const [getUser, setGetUser] = useState(null);

  useEffect(async () => {
    try {
      const { data } = await axios.post("/check",{}, { withCredentials: true });
      setGetUser(data);
      console.log("i render second")
      console.log(data);
    } catch (error) {
      console.log(error);
    }
  }, [])
  
  const { Provider } = UserContexts;
  return (
    <Provider value={getUser} >
      {console.log("i render first ")}
      {children}
    </Provider>
  )
}

export default UserContext

and here is the output :

enter image description here

the problem here that it renders Provider then the useContext that i am trying to get the data then it calls the useEffect to get the data then returns it , how can i call useEffect before all of this ?

CodePudding user response:

You can do this outside of the context, in the root of the same file:

const userPromise = axios.post("/check",{}, { withCredentials: true })

Then in useEffect do

useEffect(async () => {
    try {
      const { data } = await userPromise;
      setGetUser(data);
      console.log("i render second")
      console.log(data);
    } catch (error) {
      console.log(error);
    }
  }, [])

It will run the request at the start of the app but also would sync well with your context, correctly handling absent and loaded states

If you want to wait on it until the value is there, you could try

getUser ? <Provider value={getUser} >
      {console.log("i render first ")}
      {children}
</Provider> : null
  • Related