0

I'm working on a React dashboard and I found a library that helps me build a line chart using a json object.

So I'm trying to get 7 objects from my GET requests inside a for loop and fill the data map with them.

This is the json object that I get:

{
  "year": "2020-03-03",
  "uses": 0
}

I want to have an object like this:

data = [
  {
    year: 2014,uses: 255,
  }, {
    year: 2016,uses: 250,
  }, {
    year: 2018,uses: 540,
  },
];

I'm trying to fill the data map inside componentWillMount() like this:

constructor(props) {
  super(props);
  this.state = {
    data ,
  };
}

componentWillMount(){
  for (let i = 0; i < 7; i++) {
    axios.get("http://localhost:5000/transfer/getUsesByDay/"+i).then(
      res => {
        console.log("http://localhost:5000/transfer/getUsesByDay/"+i)
        console.log(res.data)
        //TODO : set state => Fill Data
      }
    )
  }
}

5
  • 2
    First thing to note: componentWillMount is deprecated and not suggested for use. You should use componentDidMount. Commented Mar 13, 2020 at 15:08
  • Second: what have you attempted so far to set the state, and what issues did you run into? Commented Mar 13, 2020 at 15:08
  • when i tried this : this.setState({data : res.data}) i get TypeError: data.forEach is not a function Commented Mar 13, 2020 at 15:14
  • I don't see a forEach in your code? Commented Mar 13, 2020 at 15:14
  • this is why i'm stucked , i didn't use forEach Commented Mar 13, 2020 at 15:17

1 Answer 1

2

You should use Promise.all to wait for all the response promises to resolve and then try to update the state at once.

componentWillMount() {
  let responses = []
    for (let i = 0; i < 7; i++) {
      responses.push(axios.get("http://localhost:5000/transfer/getUsesByDay/"+i))
    }

  Promise.all(responses).then(results => {
    this.setState(prevState => {
      return {
            data: [...prevState.data, ...results.map(r => r.data)]
       };
    })
  })
}

try componentDidMount instead (componentWillMount has been deprecated)

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

4 Comments

You shouldn't do prevState.data =. That mutates the state. React may not trigger a re-render.
so , what i should use instead of prevState.data ?
Thanks Brian! i have made an edit (not sure if theres any error since i did not run it myself, but conveys the idea you correctly mentioned)
Thank you for you solution , but the problem now is that i don't get the same result , axios.get doesnt seem to work in order , it executes randomly (it returns result for i = 2 , then for i equal 7 then it returns two time i = 5 per exemple)

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.