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 class extends 
Javascript :: discord.js how to send a message to all guilds 
Javascript :: remove double quotes from json array javascript 
Javascript :: discord.js edit message by id 
Javascript :: javascript date to firebase timestamp 
Javascript :: javascript sort numbers descending 
Javascript :: javascript function loop through array 
Javascript :: how to calculate the number of days between two dates in javascript 
Javascript :: change node version 
Javascript :: npm chalk 
Javascript :: remove item from array in jquery 
Javascript :: ascii code js 
Javascript :: react native strike through text 
Javascript :: use eslint in vscode 
Javascript :: Check if user logged in Wordpress through JS 
Javascript :: readfile nodejs 
Javascript :: check if input is valid js 
Javascript :: moment time format by country 
Javascript :: get client id socket io 
Javascript :: every method javascript 
Javascript :: jquery upload image 
Javascript :: javascript random number generator 
Javascript :: react string to integer 
Javascript :: if classlist contains js 
Javascript :: axios react 
Javascript :: bodyparser deprecated vscode 
Javascript :: javascript change color of text input 
Javascript :: js data object length 
Javascript :: JavaScript Use clearInterval() Method 
Javascript :: js capitalize word 
ADD CONTENT
Topic
Content
Source link
Name
3+5 =