1

Hi I am new to reactjs and I am trying to build button with a function doing some calculation by Reactjs. The logic is, first I will get two lists from database by two functions. After these 2 functions return results and setState, the calculate function will continue and do its job. But somehow the state is not being updated and it will crash. How can I secure the state is being updated before to the calculate? Thanks a lot!

Code:

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dividendList : [],
      divisorList : [],
};
}
  getDividend(){
    var self = this;
    axios.post(SERVER_NAME + 'api/getDividend', {})
        .then(function(response){
          let results = response.data;
          console.log(results)
          self.setState({ dividendList : results.data})
        })
        .catch(function(err){
          console.log(err)
        });
  } 
  getDivisor(){
    var self = this;
    axios.post(SERVER_NAME + 'api/getDivisor', {})
        .then(function(response){
          let results = response.data;
          console.log(results)
          self.setState({ divisorList : results.data})
        })
        .catch(function(err){
          console.log(err)
        });
  }

  doCal = () => {
    var self = this;
    self.getDividend();
    self.getDivisor();
    const { dividendList , divisorList} = self.state;
    # then will loop the list and do math
    # but since the state is not update, both lists are empty []
}

Tried Promise;

   getDivisor(){
    var self = this;
    return new Promise((resolve, reject) => {
      axios.post(SERVER_NAME + 'api/draw/getDivisor', {})
      .then(function(response){
        resolve(response)
      })
      .catch(function(err){
        resolve();
      });
    }) 
  } 
3
  • for a start return axios.post(... then you can either use async/await (or .then) with Promise.all ... by the way, why are your urls like api//getDivisor ... why the double / Commented Dec 1, 2020 at 3:15
  • oh typo, do you mean return the axios response data and setstate in doCal function? Commented Dec 1, 2020 at 3:21
  • if you want to wait until axio.post completes, you'll need to return that in those functions, then you can use either of the methods in the previous comment inside doCal Commented Dec 1, 2020 at 3:34

3 Answers 3

1

I think the issue here is self.getDividend(); and self.getDivisor(); are async operations. They will take some time to complete. By the time you hit the next line const { dividendList , divisorList} = self.state;, these operations are not complete and you will end up getting empty lists.

One way to address this is using moving your doCal function logic after getDividend and getDivisor are completed. You can also execute these in parallel instead of in a sequence. I used async format instead of .then(). It is just a sysntatic sugar. You can achieve the same using .then() if you prefer that way

async function doCalc() {
  const prom1 = axios.get('https://..dividentList');
  const prom2 = axios.get('https://..divisorList');
  const results = await Promise.all([ prom1, prom2]); // wait for both promise to complete
  // look inside results to get your data and set the state
  // continue doCal logic

}

Using .then()

request1('/dividentList')
.then((res) => {
    //setState for divident
    return request2('/divisorList'); // this will return a promise to chain on
})
.then((res) => {
    setState for divisor
    return Promise.resolve('Success') // we send back a resolved promise to continue chaining
})
.then(() => {
    doCalc logic
})
.catch((err) => {
    console.log('something went wrong');
});
Sign up to request clarification or add additional context in comments.

3 Comments

Hi, Yes I think so. I tried to return a promise but seems not work. I am new to async in reactjs. How can I make sure they return the list and do further step?
Thanks your code, I understand your logic. But seems it is not allow to call the "this.state" in async function? I got this when I print the state "Uncaught (in promise) TypeError: Cannot read property 'state' of undefined"
I updated answer to use .then() format. Cannot put code snipped in comment
1

I looked at your code and thought it should be changed like this to be correct.

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dividendList: [],
      divisorList: [],
    };
  }

  componentDidMount() {
    // the API just need be called once, so put here
    this.getDividend()
    this.getDivisor()
  }

  componentDidUpdate(_, prevState) {
    const { dividendList , divisorList } = this.state;
    // Ensure that the answer is only calculated once
    // the answer is only be calculated while the two list data are obtained
    if (
      prevState.divisorList.length === 0 &&
      prevState.dividendList.length === 0 &&
      divisorList.length > 0 &&
      dividendList.length > 0
    ) {
      doCal()
    }
  }

  getDividend(){
    var self = this;
    axios.post(SERVER_NAME + 'api/getDividend', {})
        .then(function(response){
          let results = response.data;
          console.log(results)
          self.setState({ dividendList : results.data})
        })
        .catch(function(err){
          console.log(err)
        });
  } 
  getDivisor(){
    var self = this;
    axios.post(SERVER_NAME + 'api/getDivisor', {})
        .then(function(response){
          let results = response.data;
          console.log(results)
          self.setState({ divisorList : results.data})
        })
        .catch(function(err){
          console.log(err)
        });
  }

  doCal = () => {
    const { dividendList , divisorList } = this.state;
    # then will loop the list and do math
    # but since the state is not update, both lists are empty []

    this.setState({ answer: 'xxx' })
  }

  render() {
    const { dividendList, divisorList, answer } = this.state

    if (dividendList.length === 0 && divisorList.length === 0) {
      return <div>Loading...</div>
    }

    if (!answer) {
      return <div>Error</div>
    }

    return <div>{answer}</div>
  }
}

The following are just some suggestions to make the code easier to read,

  1. you can use arrow function so that you don't need to write self.setState({...})
getDividend = () => {
  axios.post(SERVER_NAME + 'api/getDivisor', {})
    .then((response) => {
      let results = response.data;
      console.log(results)
      this.setState({ divisorList : results.data})
    })
    .catch((err) => {
      console.log(err)
    });
}
  1. and you can also use async/await instead of promise.then
getDividend = async () => {
  const response = await axios.post(SERVER_NAME + 'api/getDivisor', {})  
  let results = response.data;
  console.log(results)
  this.setState({ divisorList : results.data})
}

Comments

0

Set 'dividendList' and 'divisorList' equals to 'null' by default. Then, when a function that uses those lists is called, make a if statement to verify if those states goes for false (if they are still null) then return inside the function, if not, it should not crash anything.

2 Comments

Thanks for your answer, but I think this approach can only prevent the program from crashing but not update the state immediately?
yeah, it prevents the app from crashing before the lists are ready, after that you are good to go. If you are making an async request, you can't expect to have immediately access to it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.