Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

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 );
}
Comment

react native update state array of objects

let markers = [ ...this.state.markers ];
markers[index] = {...markers[index], key: value};
this.setState({ markers });
Comment

update object in array state react

const handleAdd = (todo) => {
  const newTodos = [...todos];
  newTodos.push(todo);
  setTodos(newTodos);
}
Comment

react native update state array of objects

let newMarkers = markers.map(el => (
      el.name==='name'? {...el, key: value}: el
))
this.setState({ markers });
Comment

PREVIOUS NEXT
Code Example
Javascript :: javascript pop object from array 
Javascript :: deep copy javascript 
Javascript :: looping through json array 
Javascript :: electron js hide on tray icon 
Javascript :: javascript fetch api 
Javascript :: how to use javascript to hide content and show through link 
Javascript :: javascript documentation 
Javascript :: are you sure you want to close this window javascript 
Javascript :: from json timestamp to date python 
Javascript :: javascript foreach loop array 
Javascript :: make a function and return the index of specific character in javascript 
Javascript :: best javascript books 
Javascript :: javascript prevent value change in select option 
Javascript :: split() javascript 
Javascript :: TypeError: path must be absolute or specify root to res.sendFile 
Javascript :: random color generator 
Javascript :: how to check provided value is in array in javascript 
Javascript :: spray scala JSON formatter override def read examples 
Javascript :: how to sepaarte text in object javascript 
Javascript :: javascript async await not waiting 
Javascript :: check if computer online js 
Javascript :: ajaxsetup beforesend 
Javascript :: js map delete item 
Javascript :: last index of array js 
Javascript :: 15) Which of the following directive is used to initialize an angular app? A. ng-app ANSWER B.ng-model C.ng-controller D.None of the above 
Javascript :: how to get a bot online on discord 
Javascript :: jsconfig 
Javascript :: 2d array in javascript 
Javascript :: how to send headers using swr 
Javascript :: chrome extension inject html 
ADD CONTENT
Topic
Content
Source link
Name
8+7 =