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 :: tomtom map in vuejs 
Javascript :: Run a second function only after the first function is completely finished 
Javascript :: naming a function in javascript 
Javascript :: what is from npm 
Javascript :: kjkjl 
Javascript :: proet javascript web 
Javascript :: two dimensional array object in javascript 
Javascript :: express get slash value 
Javascript :: how to add class on the base of has class in jquery 
Javascript :: r bquote subscript 
Javascript :: ggufhca spingnift cpwjirbgi bshhv 3 bvvvslit nevkdhaer nhdydg kllojb n 
Javascript :: give gray offlien scale to website 
Javascript :: how does URL.createObjectURl differ from fileReader 
Javascript :: model to js 
Javascript :: mongoose save with data from req.body 
Javascript :: george will turn g years old in year k 
Javascript :: math.random and clone 
Javascript :: langenderferc@gmail.com 
Javascript :: chrome extension how to save data to an alternative file 
Javascript :: program to parenthesize an expression 
Javascript :: UI-router accessing parent state from child 
Javascript :: <FilterProvider errorr 
Javascript :: validator.addmethod username duplicates 
Javascript :: react native generate app hash without play console 
Javascript :: npm image to LM hash 
Javascript :: Target type ieee.std_logic_1164.STD_LOGIC_VECTOR in variable assignment is different from expression type ieee.std_logic_1164.STD_ULOGIC. 
Javascript :: java jsf rendered 
Javascript :: keyup.enter will work in mac 
Javascript :: using the watch method to monitor route updates in vue 
Javascript :: simple javascript router 
ADD CONTENT
Topic
Content
Source link
Name
6+2 =