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);
    })
}
6
  • What is the issue with above code. Commented Sep 28, 2018 at 7:48
  • i want to set the state of categoryList as the Api Json Response.. just want to update the empty array with json response.. Commented Sep 28, 2018 at 7: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) }) Commented Sep 28, 2018 at 7:53
  • ouch...sorry i didnt check the code properly...thank u Commented Sep 28, 2018 at 7:54
  • Possible duplicate of setState is not updating state Commented Sep 28, 2018 at 7:55

2 Answers 2

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.

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

2 Comments

couldnt understand
well then, this is just the way React team implements the setState() method. For more information, please read this: reactjs.org/docs/react-component.html#setstate
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)
})

Comments

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.