Gaurang Shah
Gaurang Shah

Reputation: 12910

ReactJS can not access response object inside setState

I am trying to update the setSet as part of output from my RestAPI. However I am getting an error that response object is undefined. I am able to log it outside setState method.

Code

addNewTodo = () => {
axios.post('http://localhost:5001/todos', "task="+this.state.newTodoList.task)
      .then(response=>console.log(response.data))
      .then(response=>{
              this.setState(prevState=>({
                  TodoList: prevState.TodoList.push(response.data),
              }))
            });
{this.toggleNewTodoModal()}
}

I get following log in console before error

{task: "ddd", id: "todo10"}

Error:

TypeError: Cannot read property 'data' of undefined

at following line

TodoList: prevState.TodoList.push(response.data),

Upvotes: 1

Views: 43

Answers (2)

Gaurang Shah
Gaurang Shah

Reputation: 12910

My state object was a map, and so following worked for me. State

  state = {
    TodoList: {},
    }

Updating State

axios
.post('http://localhost:5001/todos', 'task=' + this.state.newTodoList.task)
.then(response => {
  const {id, task} = response.data
    this.setState(prevState => ({
        TodoList: {...prevState.TodoList,
            [id]: task},
    }));
});

Upvotes: 1

Predrag Beocanin
Predrag Beocanin

Reputation: 1400

So your first .then returns a console log, meaning your second .then will no longer have any values. If you change your code to this:

Regarding pushing new Data to react state array, The recommended approach in later React versions is to use an updater function when modifying states to prevent race conditions. So pushing new Data to state array should be something like below

axios
    .post('http://localhost:5001/todos', 'task=' + this.state.newTodoList.task)
    .then(response => {
        console.log(response.data);
        this.setState(prevState => ({
            TodoList: [...prevState.TodoList, response.data],
        }));
    });

It should work just fine. You can chain .then as much as you like, as long as you return some values, and not a console log, for example, in the fetch:

fetch('some_url', {
  method: 'GET',
})
.then(res => res.json()) // this returns the data 
.then(data => console.log(data)) // this has access to the data

Upvotes: 3

Related Questions