2

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?

2
  • Is it not safe to just use the same result that you pass to setCampaigns since calling setCampaigns will not modify result in any way? Commented Nov 16, 2019 at 8:46
  • What is the purpose? why you don't just use the result as this is only the first render Commented Nov 16, 2019 at 8:47

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

-1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.