Reputation: 33
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
.
Upvotes: 0
Views: 4155
Reputation: 1
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]);
Upvotes: 0
Reputation: 546
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);
}, []);
}
Upvotes: 0
Reputation: 2673
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.
(...) 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.
Upvotes: 3