Skip to content
Advertisement

Hook | Add Multiple List State

I define a list (useState ([])). I want to fill a list as data comes to index 0 of this list first. For example, a value comes every second and writes it on the list. then I want to press the button, create a new lite for the first index of the list and start filling it. How can I do? EX:

const [list, setList] = useState([]);
list =[
[1,2,3],
//buttonClick
[4,5],
//buttonClick
[6,7,8]
] 

Advertisement

Answer

You can use this as an example…

import { useState, useEffect } from "react";

export default function App() {
  const [list, setList] = useState([1]);

  useEffect(() => {
    // list[list.length - 1] Brings the last element from the array
    // list[list.length - 1] + 1 Increments by one to the last element
    // [...list, list[list.length - 1] + 1] Append the last element to the list
    // list.push(list[list.length - 1] + 1) will have the same effect
    setInterval(() => setList(list => [...list, list[list.length - 1] + 1]), 1000); // This will run every second
  }, []);

  // Resetting the list to an array of size 1 with the last element + 1
  const createNewList = () => setList(list => [list[list.length - 1] + 1]);

  return <div className="App">
    {list.map(item => item).join(", ")}
    <button onClick={createNewList}>New List</button>
  </div>;
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement