Answers for "update array in usestate"

CSS
1

How to add object in an array using useState

import React, { useState } from 'react';
 
function App() {
 
  const [items, setItems] = useState([]);
 
  // handle click event of the button to add item
  const addMoreItem = () => {
    setItems(prevItems => [...prevItems, {
      id: prevItems.length,
      value: getRandomNumber()
    }]);
  }
 
  // generate 6 digit random number
  const getRandomNumber = () => {
    return Math.random().toString().substring(2, 8);
  }
 
  return (
    <div classname="App">
      <h3>useState with an array in React Hooks - <a href="https://www.cluemediator.com">Clue Mediator</a></h3>
      <br>
      <button onclick="{addMoreItem}">Add More</button>
      <br><br>
      <label>Output:</label>
      <pre>{JSON.stringify(items, null, 2)}</pre>
    </div>
  );
}
 
export default App;
Posted by: Guest on December-13-2020
14

usestate array push

setTheArray([...theArray, newElement]);
Posted by: Guest on June-02-2020
3

how to set value in array react hook usestate

const[array,setArray]= useState([
        {id: 1, value: "a string", othervalue: ""},
        {id: 2, value: "another string", othervalue: ""},
        {id: 3, value: "a string", othervalue: ""},
    ])

const updateItem =(id, whichvalue, newvalue)=> {
  var index = array.findIndex(x=> x.id === id);

  let g = array[index]
  g[whichvalue] = newvalue
  if (index === -1){
    // handle error
    console.log('no match')
  }
  else
    setArray([
      ...array.slice(0,index),
      g,
      ...array.slice(index+1)
    ]
            );
}
//how to use the function    
onPress={()=>updateItem(2,'value','ewfwf')}
onPress={()=>updateItem(1,'othervalue','ewfwf')}
/*
the first input of the function is the id of the item
the second input of the function is the atrribute that you wish to change
the third input of the function is the new value for that attribute
It's a pleasure :0
~atlas
*/
Posted by: Guest on August-21-2020
1

React update state array of objects hooks

React find and update state value
Posted by: Guest on May-18-2021
0

React update state array of objects hooks

React fin and update state value
Posted by: Guest on May-18-2021

Browse Popular Code Answers by Language