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 :: how to give id dynamically in javascript 
Javascript :: functiong of array sort 
Javascript :: jshint defined variable which are coming from different file 
Javascript :: execute function after other has ended js 
Javascript :: create-react-app height issues with flex 
Javascript :: get values from string with delimiter google script 
Javascript :: https://www.npmjs.com/package/ngx-lightbox 
Javascript :: set @Output through modalref angular 
Javascript :: How to extract dynamic variable from < bracket in javascript 
Javascript :: npm i resulting in many ERESOLVE issues 
Javascript :: how to disable gravity for an object in matter.js 
Javascript :: markdown config 
Javascript :: how to catch shortcut keys in jquery 
Javascript :: whatsapp images not showing in meta tags 
Javascript :: window coordinates 
Javascript :: angular form initialse 
Javascript :: staticDir storybook svg and images not loading 
Javascript :: React uses _____________ syntax. 
Javascript :: set prop as optional in react flow 
Javascript :: jquery escape 
Javascript :: add google maps nuxt js 
Javascript :: "Perform native operation by javascript in Android" 
Javascript :: react native assembleRelease is not working 
Javascript :: class validator validate form data 
Javascript :: Make React Tooltip work for dynamic elements 
Javascript :: JS mixin implementation 
Javascript :: Function As Parameter In Self Invoking Function 
Javascript :: Change Name Of Function Constructor 
Javascript :: find parent index of nested array object javascript 
Javascript :: Return object in parenthesis to avoid it being considered a wrapping function body 
ADD CONTENT
Topic
Content
Source link
Name
3+7 =