how to set array in state in react code example

Example 1: how to update react state array

const [myArray, setMyArray] = useState([1,2,3])

// to update
setMyArray([...myArray, 4]); // --> myArray = [1,2,3,4]

Example 2: how to add array data on state react

this.setState({ myArray: [...this.state.myArray, 'new value'] }) //simple value
this.setState({ myArray: [...this.state.myArray, ...[1,2,3] ] }) //another array

Example 3: react how to update state array

const initialState = [
    { name: "foo", counter: 0 },
    { name: "far", counter: 0 },
    { name: "faz", counter: 0 }
  ];

const [state, setState] = useState(initialState);

const clickButton = () => {
	// 1. Make a shallow copy of the array
	let temp_state = [...state];
	
	// 2. Make a shallow copy of the element you want to mutate
	let temp_element = { ...temp_state[0] };
	
	// 3. Update the property you're interested in
	temp_element.counter = temp_element.counter+1;
	
	// 4. Put it back into our array. N.B. we *are* mutating the array here, but that's why we made a copy first
	temp_state[0] = temp_element;
	
	// 5. Set the state to our new copy
	setState( temp_state );
}

Example 4: react list based on state

import React, { Component } from 'react'; class App extends Component {  constructor(props) {    super(props);     this.state = {      list: [        { id: '1', age: 42 },        { id: '2', age: 33 },        { id: '3', age: 68 },      ],    };  }   onRemoveItem = id => {    this.setState(state => {      const list = state.list.filter(item => item.id !== id);       return {        list,      };    });  };   render() {    return (      <div>        <ul>          {this.state.list.map(item => (            <li key={item.id}>              The person is {item.age} years old.              <button                type="button"                onClick={() => this.onRemoveItem(item.id)}              >                Remove              </button>            </li>          ))}        </ul>      </div>    );  }} export default App;