score:6

Accepted answer

here you go, this here should work for you now. i added some notes in there.

const app = (props) => {
  const [todos, settodos] = react.usestate([
    {name: 'a', done: false},
    {name: 'b', done: false},
    {name: 'c', done: false},
  ])

  const handleclick = (name) => {
    /*
      here you were using todos.find which was returning the object. i switched
      over to todos.findindex to give you the index in the todos array. 
    */
    const index = todos.findindex(todo => todo.name === name)
    /*
      in your code you are just setting temptodos equal to todos. this isn't
      making a copy of the original array but rather a reference. in order to create 
      a copy i am adding the .slice() at the end. this will create a copy.
      this one used to get me all of the time.
    */
    let temptodos = todos.slice();
    temptodos[index].done = true;
    settodos(temptodos);
  }
  console.log(todos)
  return (
    <div>
      <h1>hello, world!</h1>
      <div>
        {todos.map((todo,index) => {
        return todo.done ? (<div key={index}>{todo.name} : done</div>) : (<div onclick={() => handleclick(todo.name)} key={index}>{todo.name} : not done</div>)
        })}
      </div>
    </div>
  )
}


reactdom.render(
  <app />,
  document.getelementbyid('root')
);

another thing i did was simplify the keys for the divs created by the map. i just added the index to the map and used that for the key, a lot cleaner that way.

hope this helps!

score:0

react won't see the state as changed unless you create a new array.

const handleclick = n => settodos(todos.map(t => t.name === n ? {...t, done: true} : t));

Related Query

More Query from same tag