Home > other >  Updating a state from another React component in ReactJS
Updating a state from another React component in ReactJS

Time:12-17

I have an api call in App.js component and I am getting the username from here to show this in the navbar. You can see the navbar component has the name property passed as a parameter to it. This is how my App.js code looks like

function App() {

  const[name,setName] = useState(null);

  useEffect(()=> {

    (
        async () => {
          try{
            const res =  await fetch('https://localhost:44361/api/users/getuser', {
                headers: {"Content-Type": 'application/json;charset=UTF-8'},
                credentials: 'include',
            });
            const content = await res.json();
            console.log(content);
            setName(content[0].uFirstName); // has to be content[0]
          }
          catch(e){
            console.log(e);
          }
        }
    )();
  },[name])
return (
    
     <Router>
       <div className="App">

           <Navbar name = {name}/>

           <Routes>

            <Route exact path="/" element={ <Home />} />

            <Route path="/registration" element = {<Registration/>} />

            <Route path="/login" element = {<Login/>} />

           </Routes>
      </div>
     </Router>
  );
}

export default App;

Now I want to update the name property from Login.js component. Login.js looks something like this:

function Login() {
    
    // const[name,setName] = useState(null);
    const[UEmail,setEmail] = useState(null);
    const[UPassword,setPassword] = useState(null);
    const[navigate, setNavigate] = useState(false);

    const submitHandler = async (e) => 
    {
        e.preventDefault(); // Prevent from being refreshed. Because User will not re-put every field if some field is wrong
        try{
            const res = await fetch('https://localhost:44361/api/users/login', {
                method: 'POST',
                headers: {"Content-Type": 'application/json;charset=UTF-8'},
                credentials: 'include',
                body : JSON.stringify({
                    UEmail,
                    UPassword
                })
            });

            var content = await res.json();

            if(res.status === 200)
            {
                  setNavigate(true);
                 //DO something
            }

            else if(res.status === 400){
                //DO something
            }
            
        }catch(err){
            console.log(err);
        }
    }
    if(navigate) // REDIRECT TO LOGIN PAGE AFTER BEING SUCCESSFULLY REGISTERED
    {
        return <Navigate to="/"/>
    }
    return (
        <div className="fullContainer">
            <div className="base-container">
                <div className="reg">Login</div>
                <div className="content">
                    <div className="form">
                        <div className="form-group">
                        
                            <input name="Email" type="email" placeholder="Email" required
                            onChange={e => setEmail(e.target.value)}
                            />
                        </div>
                        <div className="form-group">
                        
                            <input name="Password" type="password" placeholder="Password" required
                            onChange={e => setPassword(e.target.value)}
                            />
                        </div>
                    </div>
                </div>
                <div className="footer">
                    <button onClick={submitHandler} type="button" className="btn">Login</button>
                </div>
                <div className="toReg">
                <p>Don't have an account? 
                    <Link to="/registration">
                        <a> Register</a>
                    </Link>
                </p>
                </div>
            </div>
            </div>
    )
}

export default Login

How can I update the name in App.js after user click the login button after putting all credentials. I want to do this because, after navigating the user to homepage when the status code is 200 the user name is not changing in navigation bar. I need to do another reload to see the correct username in navbar.

Thank you.

CodePudding user response:

pass the callback setName from App to the Login component.

Change the function:

function Login({setName}) {

and pass the callback:

<Login setName={setName} />

Now you can call setName inside Login component

CodePudding user response:

Easer way to do this is to use context. Create one file and add in that file your variables that you want to change/use across project then wrap your project around context and finally call that method or variable in files that you wont to use it with useContext from 'react'.

You will find here everything that you need : https://www.toptal.com/react/react-context-api

  • Related