Reputation: 659
Continuous React.useState() setter does not work.
const [balance, setBalance] = React.useState(0);
const [campaigns, setCampaigns] = React.useState([]);
React.useEffect(() => {
console.log('first use Effect');
getRequest(`/api/v1/tablet/campaigns/) // getRequest return Promise Obj
.then(result => {
console.log(result); // [{...},{...},・・・,{...}]
setCampaigns(result);
console.log(campaigns); // [] this is problem part
});
}, []);
How can I refer to the value set by useState immediately afterwards?
Upvotes: 2
Views: 254
Reputation: 10873
You'd need to track it in a separate useEffect
, where you receive the updated value:
useEffect(() => {
console.log(campaigns);
}, [campaigns])
Another option is to use the value that was set on the state instead of the actual state value:
React.useEffect(() => {
console.log('first use Effect');
getRequest(`/api/v1/tablet/campaigns/) // getRequest return Promise Obj
.then(result => {
console.log(result); // [{...},{...},・・・,{...}]
setCampaigns(result);
console.log(result); // Access the result here, which is the same as campaigns
});
}, []);
Upvotes: 2
Reputation: 332
Actually it works you cant see campaigns in console because setCampaigns works async.
const [balance, setBalance] = React.useState(0);
const [campaigns, setCampaigns] = React.useState([]);
React.useEffect(() => {
console.log('first use Effect');
getRequest(`/api/v1/tablet/campaigns/) // getRequest return Promise Obj
.then(result => {
console.log(result); // [{...},{...},・・・,{...}]
setCampaigns(result);//this function works
console.log(campaigns); // but setCampaigns function works async
});
}, []);
If you want to access it immediately you need to write below code that means when change campaigns object automatically trigger useeffect function
React.useEffect(() => {
console.log(campaigns); // you can see your state data
});
}, [campaigns]);
Upvotes: -1
Reputation: 13097
You have to use the value you set it with until the next refresh of the component, as state only updates on rerender
Upvotes: 3