Home > OS >  Updating an array with useState in a form
Updating an array with useState in a form

Time:04-15

In the below, I have verified that setNewItem works, however items doesn't get updated so there must be an issue with the function handleSubmit. What is going wrong here?

import "./styles.css";
import React, {useState, useEffect} from 'react';


export default function App() {
  const [items, setItems] = useState(['first item']);
  const [newItem, setNewItem] = useState("");
  
  const handleSubmit = (event, newItem, items) => {
    event.preventDefault();
    setItems([ newItem, ...items]);
  };

  const handleChange = (event) => {
    setNewItem(event.target.value);
  }
  
  return (
    <div>
      <form>
        <input type="text" 
               value={newItem} 
               onChange={handleChange}
              />
        <input type="submit" 
               value="submit"
               onSubmit={handleSubmit}
               />
      </form> 
    <ul>
      {items.map( (i) => {
        return(<li>{i}</li>)
      })}
    </ul> 
    </div>
  );
}

https://codesandbox.io/s/new?file=/src/App.js:0-797

CodePudding user response:

try this

  • Related