reactjs – React JS: JavaScript push method replaces the last value of the array

I’m new-ish to React.js. I’m trying to make a simple Todo list app. I’m trying to use the push method to add to the array in JavaScript. I have a button that adds a todo and an input to enter the todo. Then an if/else statement determines whether or not the value of the todo input is null or an empty string. If the todo input is not null or an empty string then the following code is executed:

      todos.push(uploadTodo)
      setTodo(todos)
      console.log(todos)

This is where my problem is. todos.push(uploadTodo) will only add one new item to my array. After that it replaces the last element in the array.

Here’s my code:

import { useState } from 'react';
import Todo from './Todo'

function App() {
  let todos = ["Test", "testing"]
  const [todo, setTodo] = useState(todos)
  const [value, setValue] = useState(null)
 
  const getInput = (event) => {
    setValue(event.target.value)
  } 

  const pushTodo = (uploadTodo) => {
    if (value === null || value === "") {
      alert("Can't add an empty todo.")
    }
    else {
      todos.push(uploadTodo)
      setTodo(todos)
      console.log(todos)
    }
  }

  return (
    <>
      <h1>Todo List!</h1>
      <Todo></Todo>
      <button onClick={() => pushTodo(value)}>Add a todo</button><button>Clear todos</button><br></br>
      <input placeholder="Add a todo" onChange={getInput}></input>
    </>
  );
}

export default App;

I’m using the latest version of React.js (As of now 18.2.0).

Read more here: Source link