react hook useState can not store json or string

As the title say, the react hook useState seemed can not store my string

here is my code

const [data, setData] = useState(null);
useEffect(() => {
        fetch("http://api.localhost/user/shoppingcart", {
            headers: {
                Authorization: cookies.Authorization
            }
        })
            .then(res => res.json())
            .then(
                result => {
                    console.log(result);
                    setData(result);
                    console.log(data);
                });
    }, []);

the first “console.log”, I can get the correct string.

[{"shoes":1}, {"shirt":2}]

but the second “console.log”, I get a null string.

null

or maybe my mistake?

Answer

setState is async. So you cannot get the data right after setting the state.

You will always get previous state if you try to console.log state after setting state.

If you want to get new data, then you should have dedicated useEffect hook with dependency array,

useEffect( () => {
   console.log(data)
},
[data] //This is dependency and it will run only when data is changed
) 

Leave a Reply

Your email address will not be published. Required fields are marked *