Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React componentDidMount setState but return undefined

I can get list with get axios.get method. then ı can use setState and it works flawlessly.
but the return is not true , its return undefined console.log(result) => undefined . How can ı check if setState work fine return true or return false ?

getList = async () => {
  await axios.get("http://localhost:5000/list").then((response) => {
    this.setState(
      {
        copy: response.data.list,
      },
      () => {
        return true;
      },
    );
  });
};

componentDidMount = () => {
  this.getList().then((result) => {
    console.log(result);
  });
};

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Your return true statement is in setState‘s post-set callback. It won’t be propagated to the promise that’s returned from getList; indeed, you return nothing from that function (you don’t even return the Axios promise; if you did return that, you would get the response logged in your console.log, but it would be logged before the setState callback finished), so you get undefined in the console.log.

If you need getList to return a promise that resolves to true once the state has been set, you’ll need

getList = () => {
  return new Promise((resolve) =>
    axios.get("http://localhost:5000/list").then((response) =>
      this.setState(
        {
          copy: response.data.list,
        },
        () => resolve(true),
      ),
    ),
  );
};

componentDidMount = () => {
  this.getList().then((result) => {
    console.log(result);
  });
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading