Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use AppState in a functional component and hooks? Necessary or am I using useEffect incorrectly?

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?

like image 633
hellomello Avatar asked Jan 12 '20 18:01

hellomello


1 Answers

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();
  }
}
like image 130
fayeed Avatar answered Oct 08 '22 23:10

fayeed