Basically, I'm trying to change a React's state by calling a setter method in another function. The first 2 methods changes my state, but the third one doesn't do so right away (I bound all the calls to an onClick event and then just went ham on the button)
const [var1, setVar1] = useState(null)
const foo = () => {
console.log(var1)
setVar1("hello world")
console.log(var1)
}
...<button onClick={foo}>test</button> //logs("hello world" ; "hello world")
...<button onClick={() => {foo()}}>test</button> //logs("hello world" ; "hello world")
...<button onClick={() => {foo("test")}}>test</button> //logs(null ; null) //pressing again log("hello world"; "hello world")
Funnily enough, if I changed foo to accept AND uses a variable, the third call would log ("hello world", "hello world"), but if I don't use the variable it'll return null on the first try, then on second click it'll show the state being changed
const foo2 = (testVar) => {
console.log(var1)
setVar1(testVar)
console.log(var1)
}
...<button onClick={() => {foo2("hello world")}}>test</button> //logs("hello world"; "hello world")
const foo3 = (testVar) => {
console.log(var1)
setVar1("the inner hello world")
}
...<button onClick={() => {foo2("hello world")}}>test</button> //logs(null; null) // second click onward logs ("the inner hello world"; "the inner hello world")
Also, while we're on this topic, does anyone know why it logs "hello world" even before the setter setVar1() get called?