0
myVals = ['hi','there']; //These are actually ready from the input

const [myVals , setMyVals ] = React.useState(props.myVals);

Using the removeMyVals function, I'm trying to remove the selected value based on the index. I'd like to pass the updated myVals to updateCalledInAnotherFile which is used in another file.

However, it seems like on doing this, the myVals hasn't been updated with the most recent array after removing one of the strings.

Basically, if I remove 'there', then I'm trying to update myVals = ['hi']

From this previous question - The useState set method is not reflecting a change immediately I understand that React.useEffect() could be what I'm looking for. However, I also understand that useEffect() cannot be called from within a function. In my case I want the variable myVals to be updated immediately since this value needs to be passed to another file.

Is there any way I can do this immediately?

const removeMyVals = (indexToRemove: number) => {
   setMyVals([
     ...myVals .slice(0, indexToRemove),
     ...myVals .slice(indexToRemove + 1),
   ]);
  props.updateCalledInAnotherFile(myVals); 
};
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
curiousCat
  • 157
  • 3
  • 11

0 Answers0