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())
                result => {
    }, []);

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

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

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


or maybe my mistake?


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( () => {
[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 *