Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

321
Visualizações
How can I fix setState() so that it works?

I'm following Bob Ziroll's free scrimba course on React.

Thing is, my code is the same with his and it has been working so far...

but it isn't working anymore.

Here's my code

App.js

import React, { Component } from "react";
import TodoItem from "./components/TodoItem";
import todosData from "./components/todosData";

class App extends Component {
  constructor() {
    super()

    this.state = {
      todos: todosData
    }
    
    this.handleChange = this.handleChange.bind(this)
  }

  handleChange(id) {
    this.setState(prevState => {
      console.log("PrevState Start ", prevState.todos )
      const updatedTodos = prevState.todos.map(todo => {
        if (todo.id === id) {
          todo.completed = !todo.completed
        }
        return todo
      })

      return {
        todos: updatedTodos
      }
    })

    console.log("Changed", id)
    
  }

  render() {
    const todoItem = this.state.todos.map(x => 
      <TodoItem handleChange = {this.handleChange}
        key={x.id} 
        item={x}
      />
    )

    return (
      <div>
        {todoItem}
      </div>
    );
  }
}

export default App;

And here's the code for TodoItem.js

import React from 'react'

function TodoItem(props) {
    return (
        <div>
            <input type='checkbox' checked={props.item.completed} onChange={() => props.handleChange(props.item.id)} /> 
            <p>{props.item.text}</p>
        </div>
    )
}

export default TodoItem

And here's todosData.js*

const todosData = [
    {
        id: 1,
        text: "Take out the trash",
        completed: true
    },
    {
        id: 2,
        text: "Grocery shopping",
        completed: false
    },
    {
        id: 3,
        text: "Clean gecko tank",
        completed: false
    },
    {
        id: 4,
        text: "Mow Lawn",
        completed: true
    },
    {
        id: 5, 
        text: "Catch up on arrested development",
        completed: false
    }
]

export default todosData

I've tried using a callback but it isn't working. I've checked prevState and the updated state, but no change is reflected.

I'd appreciate your help on this.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

When you are updating the state using setState, You should return new object to tell react that this is the change and React will update it accordingly.

Live Demo

Codesandbox Demo

React will compare the reference of two objects and if you won't return new object then react will take as a same object. React won't figure out when you won't return new object. You are just updating a property of an object as :

if (todo.id === id) {
   todo.completed = !todo.completed
}

You just have to make a small change as:

if (todo.id === id) {
   return { ...todo, completed: !todo.completed };
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Being super curious, I tried your code and it works perfectly for me. Is this not what you wanted to happen? Check the snippet below:

document.onreadystatechange = () => {
  const { useState, Component } = React;

  class App extends Component {
    constructor() {
      super();

      this.state = {
        todos: todosData,
      };

      this.handleChange = this.handleChange.bind(this);
    }

    handleChange(id) {
      this.setState((prevState) => {
        console.log("PrevState Start ", prevState.todos);
        const updatedTodos = prevState.todos.map((todo) => {
          if (todo.id === id) {
            todo.completed = !todo.completed;
          }
          return todo;
        });

        return {
          todos: updatedTodos,
        };
      });

      console.log("Changed", id);
    }

    render() {
      const todoItem = this.state.todos.map((x) => (
        <TodoItem handleChange={this.handleChange} key={x.id} item={x} />
      ));

      return <div>{todoItem}</div>;
    }
  }

  function TodoItem(props) {
    return (
      <div>
        <input
          type="checkbox"
          checked={props.item.completed}
          onChange={() => props.handleChange(props.item.id)}
        />
        <p>{props.item.text}</p>
      </div>
    );
  }

  const todosData = [
    {
      id: 1,
      text: "Take out the trash",
      completed: true,
    },
    {
      id: 2,
      text: "Grocery shopping",
      completed: false,
    },
    {
      id: 3,
      text: "Clean gecko tank",
      completed: false,
    },
    {
      id: 4,
      text: "Mow Lawn",
      completed: true,
    },
    {
      id: 5,
      text: "Catch up on arrested development",
      completed: false,
    },
  ];

  ReactDOM.render(<App />, document.querySelector("#root"));
};
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>

<div id="root"></div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda