0

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?

Mateus Ramos
  • 190
  • 2
  • 12
  • 1
    Yes, that behaviour's expected. If you want to update the effect when the value of foo changes, it needs to be a dependency. The `console.log(foo);` immediately after `setFoo` is *inevitably* the old value, because we can't possibly have hit `useState` again yet. – jonrsharpe Jun 30 '20 at 19:58
  • Thanks a lot, that solved my problems. – Mateus Ramos Jun 30 '20 at 20:01

0 Answers0