showing results for - "add object to array setstate"
Rafael
04 Jun 2020
1import React, { useState } from 'react';
2 
3function App() {
4 
5  const [items, setItems] = useState([]);
6 
7  // handle click event of the button to add item
8  const addMoreItem = () => {
9    setItems(prevItems => [...prevItems, {
10      id: prevItems.length,
11      value: getRandomNumber()
12    }]);
13  }
14 
15  // generate 6 digit random number
16  const getRandomNumber = () => {
17    return Math.random().toString().substring(2, 8);
18  }
19 
20  return (
21    <div classname="App">
22      <h3>useState with an array in React Hooks - <a href="https://www.cluemediator.com">Clue Mediator</a></h3>
23      <br>
24      <button onclick="{addMoreItem}">Add More</button>
25      <br><br>
26      <label>Output:</label>
27      <pre>{JSON.stringify(items, null, 2)}</pre>
28    </div>
29  );
30}
31 
32export default App;
33
Camilla
26 Oct 2017
1To push to the beginning of the array do it this way
2
3   this.setState( prevState => ({
4     userFavorites: [{id: 3, title: 'C'}, ...prevState.userFavourites]
5  }));
similar questions
queries leading to this page
add object to array setstate