0
const [action, setAction] = useState(true);
const sharedVal = useSharedValue(action ? 10 : 20)
useEffect(() => {
    setTimeout(() => {
        setAction(false)
    }, 2000)
}, [])

In the above code, the value of shareVal doesn't change the value of action changes. What is the best way to update value of sharedVal after the timeout.

3 Answers3

3

you'll have to run a side effect when action changes.

useEffect(() => {
  
  sharedVal.value = action ? 10 : 20;

  // this will run when action is updated 
}, [action]);

or you can just do sharedVal.value = someValue wherever you want.

documentation

(...) The reference is an object with .value property, that can be accessed and modified from worklets, but also updated directly from the main JS thread.

LonelyCpp
  • 2,533
  • 1
  • 17
  • 36
  • This is definitely how it should be done, but tbh I have a lot of inconsistencies in the updates with this method – Alec Mather Oct 15 '22 at 04:50
0

Try this way

function Example() {
  const [action, setAction] = useState(true);

  React.useEffect(() => {
    async function useSharedValue(number) {
      const response = await fetch(....);
      const json = await response.json();
      setAction(true); // reset state here
    }

    useSharedValue(action ? 10 : 20);
  }, []);
}
Surya
  • 546
  • 7
  • 13
0

I have a code similar to yours. UseEffect is called every time there is a change in the alert variable, as you can see in my code bellow. If the second argument is empty [], useEffect will only be executed once when the page is loaded. As you want to call every time there is a change in the value of the action variable, just place it inside [].

    useEffect(() => {
       if (alert != '') setTimeout(() => { setAlert('') }, 4000);
    }, [alert]);