1

I am working on a todo application in reactjs. I am using object in react state for title and task. The issue is whenever I try to merge old state with new one it does not work.

Please check my code below.

const [todo, setTodo] = useState({ title: "", task: ""});

const setObj = { title: valueOfTile, task: valueOfTask};

setTodo({...todo , ...setObj});

Also how can I iterate through them? This is what I am doing to iterate:

{Object.keys(todo).map((data, i) => (
    <div className="main " key={data}>
      <div CLASSNAME="first">
        <h1>{todo.title}</h1>
      </div>
      <div className="second">
        <p>{todo.task}</p>
      </div>
    </div>
  ))}

I am not sure why I am getting two rows for one added title and task. Check imageenter image description here

2 Answers 2

1

Change your state with this:

const [todo, setTodo] = useState([]);

Then, change this

setTodo({...todo , ...setObj});

with this:

setTodo([...todo, setObj]);

You don't need to use spread operator on setObj. Currently you are adding two items to your state. That's why you are getting two rows.

For mapping, you can do something like this:

{ todo.map( (data, index) => {
    // Your code
})
Sign up to request clarification or add additional context in comments.

Comments

0
  1. Your first question (update state) needs more information, please give complete code.
  2. Object.keys(todo) will return ["title", "task"], so ["title", "task"].map(function())'s function in map will execute twice time, and results render 2 <div>.

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.