How to reassign/replace a value of an array by index if its in a global state

126 views Asked by At

I have a global state that is an array [1,0, null,1,0....] I want to access the array by index let's say index 5 I want just to replace that value with 1 I have the array and I have the index but I don't know how to reassign and update the state

const setarrayFlags = useSetRecoilState(arryofFlags); //setting my global array
const setPosition = useSetRecoilState(Position); // I keep track of the position 

setarrayFlags([1,0,null,1,0...); // set array with values

// This is called from a child componet
 const arryofFlag = useRecoilValue(arryofFlags); // get my global array
 let FlagPosition = useRecoilValue(Position);  // get current position

arryofFlag[FlagPosition] = 1; // this is how I reassign the value on the current position but not sure how to use setarrayFlags again to set it global again without replacing the whole array just that position    

setarrayFlags(arryofFlag[FlagPosition] = 1); //cant be this way
1

There are 1 answers

0
Yasser hennawi On BEST ANSWER

So, instead of this line arryofFlag[CardPosition] = 1;, you can write:

const tempArray = [...arryofFlags];
tempArray[CardPosition] = 1
setarrayFlags(tempArray)