Reputation: 327
I am having trouble when updating an array using the useState hook. What i want is i have an array filled with n number of elements where n could be 1-10. and i want to update the value of an element using its index no. but i am not getting any help. Here's the codes what i want to acheive:
import React, {useState} from 'react';
import React, {View, Text} from 'react-native';
const myScreen = props => {
const [myCustomArray, setmyCustomArray] = useState(Array.(5).fill(0));
const onClickHandler = (n) => {
// update the element in array having the index no. n
setMyCustomArray([n] = 'something');
}
But this approach is not helping me. Anyone have better approach?
Upvotes: 3
Views: 4222
Reputation: 141
you should spread the array before that
const onClickHandler = (n) => {
const arr = [...myCustomArray];
arr[n] = 'something';
setMyCustomArray(arr);
}
react checks the reference of the array, if changed then rerender, else don't.
Upvotes: 9