react hooks add to array code example
Example 1: usestate array push
setTheArray([...theArray, newElement]);
Example 2: 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){
console.log('no match')
}
else
setArray([
...array.slice(0,index),
g,
...array.slice(index+1)
]
);
}
onPress={()=>updateItem(2,'value','ewfwf')}
onPress={()=>updateItem(1,'othervalue','ewfwf')}
Example 3: add items to a react array in hooks
const addMessage = (newMessage) => setMessages(state => [...state, newMessage])
Example 4: add items to a react array in hooks
const addMessage = (newMessage) => setMessages(state => [newMessage, ...state])