1this.setState(prevState => ({
2 myArray: [...prevState.myArray, "new value"]
3}))
4
1how to add array data on state react
2this.setState({ myArray: [...this.state.myArray, 'new value'] }) //simple value
3this.setState({ myArray: [...this.state.myArray, ...[1,2,3] ] }) //another array
1this.setState({ myArray: [...this.state.myArray, 'new value'] }) //simple value
2this.setState({ myArray: [...this.state.myArray, ...[1,2,3] ] }) //another array
3
1const initialState = [
2 { name: "foo", counter: 0 },
3 { name: "far", counter: 0 },
4 { name: "faz", counter: 0 }
5 ];
6
7const [state, setState] = useState(initialState);
8
9const clickButton = () => {
10 // 1. Make a shallow copy of the array
11 let temp_state = [...state];
12
13 // 2. Make a shallow copy of the element you want to mutate
14 let temp_element = { ...temp_state[0] };
15
16 // 3. Update the property you're interested in
17 temp_element.counter = temp_element.counter+1;
18
19 // 4. Put it back into our array. N.B. we *are* mutating the array here, but that's why we made a copy first
20 temp_state[0] = temp_element;
21
22 // 5. Set the state to our new copy
23 setState( temp_state );
24}