im using useState to store an object, with one property boolean, and using ternary operator to get the switch between screens.
when i click the button, i see in the console that the value is changed but the screen doesn't update, doesnt show "i'm in", the console show this:
{logged: false, name: 'example'} Login.js:7
{logged: true, name: 'example'} Login.js:9
When i change the useState to a single variable, not an object, works (changing the childrens), but a i really want to use with an object. So i want to know why isn't working, is some property of useContext? or limitation on useState? meanwhile i will use useState with a single asignation (boolean) an multiple variables-lines
The reason to use useContext is for pass down the variables, in case of many layers of childrens
App.js
import React, { useState } from "react"
import AppMain from './Components/AppMain';
import Login from './Components/Login';
import ExampleContext from "./ExampleContext";
function App() {
const [user, setuser] = useState({"logged" : false, name: "example"})
return (
<ExampleContext.Provider value={{ user, setuser }}>
{user.logged? <AppMain />:<Login />}
</ExampleContext.Provider>
);
}
export default App;
AppMain.js
import React from "react"
function AppMain() {
return (
<>
<p>I'm in</p>
</>
)
}
export default AppMain
Login.js
import React, { useContext } from "react"
import ExampleContext from "../ExampleContext"
function Login() {
const {user,setuser} = useContext(ExampleContext)
function log(){
console.log(user)
setuser(a=> {a.logged = true; return a})
console.log(user)
}
return (
<>
<button onClick={log} >Log in</button>
</>
)
}
export default Login
ExampleContext.js
import { createContext } from "react"
const ExampleContext = createContext()
export default ExampleContext
Nothing is wrong with useState or useContext, your way of mutating state is wrong. set it this way:
setuser(a=>({...a,logged:true}));