I have a variable declared inside of a const in React. When I change it, the content on my screen changes, the content inside the return() of the const. However, the value inside other places that isn't the return method doesnt change.
export const SomePage = () => {
const [foo, setFoo] = React.useState<string>("");
const getValueFromServer = () => {
axios.get("/server")
.then((result) => {
console.log(result.data.someValue); // prints the expected value, contained in the server response object
setFoo(result.data.someValue);
console.log(foo); // prints <empty string> / initial value
}
React.useEffect(() => {
const interval = setInterval(() => {
console.log(foo); // always print initial value <empty string>
}, 1000);
return () => {
clearInterval(interval)
}
}, []);
const renderContent = () => {
<div>{foo}</div> // this shows the foo value that came from the server response
}
return( renderContent );
Is this behavior expected? Inside the method "getValueFromServer" I understand it could just be executing asynchronous so thats ok that the console.log is called before the setFoo ends. But the method that keeps getting called shouldn't be updated at some point? How can I make it update?