Home > Back-end >  How to reassign/replace a value of an array by index if its in a global state
How to reassign/replace a value of an array by index if its in a global state

Time:05-26

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

CodePudding user response:

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

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