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("/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?
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?
Share Improve this question edited Oct 19, 2019 at 6:22 Jee Mok 6,5668 gold badges53 silver badges83 bronze badges asked Oct 19, 2019 at 3:32 John YoungJohn Young 571 silver badge8 bronze badges 1- Possible duplicate of Executing async code on update of state with react-hooks – Jay Jordan Commented Oct 19, 2019 at 3:42
2 Answers
Reset to default 6setState
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
)
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.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744248076a4565034.html
评论列表(0条)