Unable to map over array-React-Hooks

hello everyone, so I started building a Todo app using create-react-app and hooks. I seem to have a issue trying to map over the todos array and display the indexes as <li></li> can anyone help me? In the browser its says todos is undefined.

import './App.css';
import React, { useState } from 'react'

function App() {

  const [ { input, todos }, setTodo ] = useState({input:"", todos:[]});

  const handleChange = (e) => {
    setTodo(() =>({
      input: e.target.value
    }));
  };

  const handleTodo = ()=>{
    setTodo(()=>({
      todos: todos.push(input)
    }))
  }

  return (
    <div className="App">
      <div className="container">

        <div className="todo-input">
          <h2>Add a ToDo...</h2>
          <input type="text" className="input" placeholder="New Todo..." value={input} onChange={handleChange}></input>
          <button className="add-todo" onClick={handleTodo}>Add Todo</button>
        </div>

        <div className="todo-items">
          <ul>
            {todos.map((arr,i)=>{
              let x = <li key={i}>{arr[i]}</li>;
              return x;
            })}
          </ul>
        </div>

      </div>
    </div>
  );
}

export default App;

That’s because both of your handlers sets only one of the state keys effectively deleting the other one.
It’s better to use separate useState for input and todos.

I agree that you should use separate state variables/setters. There is really no added benefit to managing the state as an object here.

I think you are trying to use useState like setState. I would suggest you check out the docs and some articles/tutorials on using React hooks.


Also, note that the first parameter to map is the array element, not the array. You do not have to use an index to get to the element.

[1, 2, 3].map((element, index, originalArray) => console.log({element}, {index}, {originalArray}))

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.