Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React .push is not a function

I’m trying to make a to-do app.

First, I detect the change in the input and assign it to the state named todo.

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

then i try to add the information in todo to the todos state, which is empty array when the button is clicked.

const [todos, setTodos] = useState([]); 
    const handleClick = () => {
    setTodos(todos.push(todo));
    console.log(todos);
}[enter image description here][1]

At the first click, it adds as seen below.
However, on the second click I get the following error: Uncaught TypeError: todos.push is not a function

console log

The full code is as follows:

  const [todo, setTodo] = useState(""); 
const [todos, setTodos] = useState([]); 

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

const handleClick = () => {
    setTodos(todos.push(todo));
    console.log(todos);
}

return(
    <>
        <input type="text" onChange={handleChange} />
        <button onClick={handleClick}>add</button>
    </>
)

}

I’m wondering where i went wrong.

>Solution :

Use the spreeeeead opperraattoorrrrr 🕺

Also you state mutation won’t update in time for the console log below to be fired, use a useEffect() and pass todos as the dependancy for it to watch for updates on and pass the console log into there.

 const [todo, setTodo] = useState(""); 
const [todos, setTodos] = useState([]); 

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

const handleClick = () => {
    setTodos([...todos, todo]);
    // This will spread in the previous todos, then place todo within the array.

   setTodo('');
   // also, looking at your code, you probably need to empty todo afterwards.
}

useEffect(() => {
  console.log(todos);
}, [todos])

return(
    <>
        <input type="text" onChange={handleChange} />
        <button onClick={handleClick}>add</button>
    </>
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading