0

I have a program that uses Axios to get data with API calls. I want to store the result as a object in my this.state.matrixDictionary variable. but everytime i make another API call the previous object gets overwritten. I want to create something like this

this.setState({
     matrixDictionary: {
       [0]: result,
     }
}) 

Then next time i make another api call to get other result i want it to be like this:

this.setState({
     matrixDictionary: {
       [0]: result,
       [1]: result,
     }
})

But i dont want to add the [1] manually, i want it to be created depending on how many times i make the API call to store the objects. If i make 5 calls then the object should be now [0],[1],[2],[3],[4] so i can easily keep track of the objects and change their values later.

How is this best achieved?

fetchDataAPI(APIUrl){


    this.setState({ isLoading: true });
    console.log("Fetching from: " + APIUrl);

    return axios.get(APIUrl,{
        headers: {
            "Accept": "application/json",
            "Content-Type": "application/json"
        }
    })
        .then(result => {
            this.setState({isLoading: false});
            console.log(result.data);
            return result.data;
        })
        .catch(error => {
            this.setState({error, isLoading: false })});

}

UPDATE

I used the fix from Roman Batsenko, Next question is how do I then change a property in that object and put it back in setState.

gtag
  • 53
  • 1
  • 2
  • 7

3 Answers3

0

I guess good practice is to use JS Spread syntax for that like ...state. It depends on the format of answer from your API but I think it would be not so hard to achieve this with:

axios.get(APIUrl,{
    /* ... */
})
    .then(result => {
        this.setState({
            isLoading: false,
            matrixDictionary: [...this.state.matrixDictionary, result.data]
        });
    })
0

make an array of object in your intial state like

this.state = {
         matrixDictionary: []
      }

and when you call your api push your response object in array so that will store always in another index and finally you make array of objects.

this.setState({ matrixDictionary: result.data});

it may help you.

0

Why not save the objects in an array, so you can have them in order:

in the constructor:

this.state = {
  matrixDictionary: []
}

in your API call:

this.setState(prevState => ({
  values: prevState.matrixDictionary.concat(result.data),
}));

You can access them like this:

this.state.matrixDictionary[0] // your first api call
this.state.matrixDictionary[1] // your second api call
this.state.matrixDictionary[2] // your third api call
c-chavez
  • 7,237
  • 5
  • 35
  • 49