I want to be able to run a function when a user goes into the app. I thought useEffect would already do something like this, say if I choose to change my phone's Clipboard (copy different texts from another app). But its not rerendering the component.
const [clipped, setClipboard] = useState();
const [appView, setAppView] = useState(AppState.currentState);
const getFromClipboard = useCallback(() => {
Clipboard.getString().then(content => {
console.log('content:', content)
setClipboard(content);
});
}, [clipped]);
useEffect(() => {
getFromClipboard();
}, [getFromClipboard, clipped, appView]);
I would assume that every time I copy a new text from a different app, into my clipboard, and then I go back to this app, because the state changed in clipped, it will rerender the useEffect? Unfortunately, its not calling the console log after first initial load of the component.
I stumbled across AppState, and thought I might be able to give this a shot, but not sure how to set this up with useEffect?
You can set an event listener for app state change it will trigger when the app is closed, moved to background or foreground, You can check the documentation for more details link:
useEffect(() => {
AppState.addEventListener('change', handleChange);
return () => {
AppState.removeEventListener('change', handleChange);
}
}, []);
const handleChange = (newState) => {
if (newState === "active") {
getFromClipboard();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With