简体   繁体   中英

How can I refer to the value set by useState immediately afterwards?

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?

You have to use the value you set it with until the next refresh of the component, as state only updates on rerender

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
  });
}, []);

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]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM