Home > other >  react global context is not updating
react global context is not updating

Time:01-18

I am relatively new to react and cant seem to get my global context to update.I have wrapped all my child components with the provider but it seems like my update methods in my useState() variables are not working as expected. In my index.js file, I wrap my App component in the provider first:

import App from './App';
import reportWebVitals from './reportWebVitals';
import {
  BrowserRouter,
  Route,
  Routes
} from "react-router-dom";
import {UserContextProvider} from './components/UserContext';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(

<UserContextProvider>
  <App/>
</UserContextProvider>
);

Here is my UserContext.js file:

import React from "react";
import { useState, createContext } from "react";

export const UserContext = createContext({})
export const UserContextProvider = ({children}) =>{
const [contextUsername, setUserName] = useState(null)
const [contextFirstname, setFirstName] = useState(null)
const [contextLastname, setLastName] = useState(null)
const [contextLoggedin, setLoggedIn] = useState(false)

const value={contextUsername, setUserName, contextFirstname, setFirstName, 
contextLastname,setLastName,contextLoggedin,setLoggedIn}

return(
    <UserContext.Provider value={value}>
        {children}
    </UserContext.Provider>
)

}

I am trying to access my context in my Landing component:

import React, { useContext } from 'react';
import { useState } from 'react';
import {Link, useNavigate} from "react-router-dom"
import { UserContext } from './UserContext';
const Landing = () =>{
    const {contextUsername,setUserName} = useContext(UserContext)

    const onExit = (convertedData) =>{
            setUserName("test")
            console.log(contextUsername)
            navigate('/');
     }
    return(
        <div> 
           <button onLick={onExit}></button>
        </div>
    )
    }
    export default Landing

However, in my console.log statement my contextUsername is 'undefined'.

CodePudding user response:

The update state doesn't work like that. react create a queue for state update so we can not get the latest value right after the update call. since you are console.log(contextUsername) right after setUserName it console's undefined.

and don't pass updateState-method(ex. setUserName) directly in context create method to change state value from there call updateState-method(ex. setUserName) like

const UpdateUserName = (value) =>{
  setUserName(value)
}

if you want to check the updated value of contextUsername use useEffect

  useEffect(() => {
     console.log(contextUsername);
  },[contextUsername])
  • Related