1

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?

Jee Mok
  • 6,157
  • 8
  • 47
  • 80
John Young
  • 57
  • 1
  • 8
  • Possible duplicate of [Executing async code on update of state with react-hooks](https://stackoverflow.com/questions/53898810/executing-async-code-on-update-of-state-with-react-hooks) – Jay Jordan Oct 19 '19 at 03:42

2 Answers2

6

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
) 

ravibagul91
  • 20,072
  • 5
  • 36
  • 59
  • Also, event if setData was synchronous, data would still have null, because of the line `const [data, setData] = useState(null);` will not be executed until the next render. – Vikash Kesarwani Oct 19 '19 at 03:46
0

The title of the question is misleading. I mean, it doesn't matter it is json string or not. The solution is as simple as moving the console.log(data); out of the useEffect block and right after return(if before return won't be able to response). And that might be what the original poster wanted.

letmeask
  • 43
  • 7