Home > Back-end >  UseState in To do List REACT
UseState in To do List REACT

Time:11-29

In the browser returns the input in the list when I placed, but in the same second disappears. Until the end of the function the array is fulfill, when refresh the response the array "does" is empty. Something is wrong and the state is not storing.

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

function App() {
  const [text1,setText1] = useState('');
  const [does,setDoes] = useState([]);
  
  function addTodo(){
    
   return setDoes([...does,text1]);
  
    
  }
  return (
    <div>
      <h1>To do List!</h1>
      <form onSubmit={addTodo}>
        <input type="text" name='text1' id='text1' placeholder='To do' onChange={(e)=>setText1(e.target.value)}/>
        <button type="submit" className="submitButton">Add</button>
        
      </form>
      
      <ul className='todoo'>
        {does.map(item => <li key={item.toString()}>{item}</li>)}
      </ul>
      
    </div>
  );
}

export default App;

I expect to storage the tasks...

CodePudding user response:

To not disappear when you place a text and click add use e.preventDefault() Like this:

function App() {
  const [text1, setText1] = useState("");
  const [does, setDoes] = useState([]);

  const addTodo = (e) => {
    e.preventDefault(); 
    return setDoes([...does, text1]);
  };

  return (
    <div>
      <h1>To do List!</h1>
      <form onSubmit={(e) => addTodo(e)}>
        <input
          type="text"
          name="text1"
          id="text1"
          placeholder="To do"
          onChange={(e) => setText1(e.target.value)}
        />
        <button
          type="submit"
          className="submitButton"
        >
          Add
        </button>
      </form>

      <ul className="todoo">
        {does.map((item) => (
          <li key={item.toString()}>{item}</li>
        ))}
      </ul>
    </div>
  );
}
export default App;

and if you want to keep the data in the page when you refresh it you can either use an api to store the data to a database or to use localStorage. enter image description here

  • Related