1

I have set the state of a array as [] empty, in componentDidMount i am getting the API Response.. now i want to set the state of the empty array with the new array of json response how can i do this?

constructor(props)
{
    super(props)
    this.state = {
        categoryList : []
    }
}
componentDidMount()
{

    axios.get('http:xxxxxxxxxxxxxxxxxxxxxxx')

    .then(res => 
    {
        this.setState = {
            categoryList : res.data.body.category_list(json path)
        }
    })
    .catch(function(error) {
        console.log('Error on Authentication' + error);
    })
}
Ramya MiiM
  • 245
  • 2
  • 4
  • 11
  • What is the issue with above code. – RIYAJ KHAN Sep 28 '18 at 07:48
  • i want to set the state of categoryList as the Api Json Response.. just want to update the empty array with json response.. – Ramya MiiM Sep 28 '18 at 07:49
  • setState is a method, you need to call it with the object/updater function, remove `=`, like this: `this.setState({ categoryList : res.data.body.category_list(json path) })` – Mayank Shukla Sep 28 '18 at 07:53
  • ouch...sorry i didnt check the code properly...thank u – Ramya MiiM Sep 28 '18 at 07:54
  • Possible duplicate of [setState is not updating state](https://stackoverflow.com/questions/43323907/setstate-is-not-updating-state-reactjs/43323950#43323950) – Mayank Shukla Sep 28 '18 at 07:55
  • @Ramya MiiM consider accepting any one of the answer whichever resolves your issue so that the thread will be closed and that will help future readers – Hemadri Dasari Oct 13 '18 at 20:48

2 Answers2

1

Try this:

 this.setState({
    categoryList : res.data.body.category_list(json path)
 })

because setState() method accepts an object which will be merged with the current state.

You Nguyen
  • 9,961
  • 4
  • 26
  • 52
1

You need to understand two things here

Below functionality is for initializing the states with initial values

this.state = {
  categoryList: []
}

To modify the categoryList state or any other state variable you need to use setState method like below. Keep in mind setState is a method

this.setState({
  categoryList : res.data.body.category_list(json path)
})
Hemadri Dasari
  • 32,666
  • 37
  • 119
  • 162