3

I have a custom modal with custom buttons as props.

const [selection,setSelection] = useState(null)

    const onSelect = (item) => {
      setSelection(item);
   
      Gui.PickOption({
          message: 'choose an action',
          buttons: BUTTONS,
          onPress,
      });
    }; 
BUTTONS = [{buttonText:'print selection', onPress:()=> console.log(selection)}]

the issue here is that when the user presses the button, the log will be NULL because it seems that the modal has the state before the "selection" was updated. why doesn't it updated? how to make BUTTONS keep up with state changes? ( keep in mind the code above is a small example for an issue I am currently facing) , essentially I want the onPress to always perform set "tasks" with the most "current" state. )

lord_drgical
  • 143
  • 2
  • 8

1 Answers1

2

The problem is you used selection value, right after setState. I guess you can use a useEffect which listens to selection value and perform your logics there like:

const [selection, setSelection] = useState(null);
const onSelect = (item) => {
    setSelection(item);
};
useEffect(() => {
    Gui.PickOption({
        message: "choose an action",
        buttons: BUTTONS,
        onPress,
    });
}, [selection]);

When you set some state (here setSelections), your component re-renders with the new value, but in onSelect button's function you still running with the old value (until the next use, which is the next render).

Pooya Haratian
  • 765
  • 4
  • 16