Last active
          September 9, 2021 04:57 
        
      - 
      
- 
        Save wobsoriano/cef283120db9c5748207f423b7726a6f to your computer and use it in GitHub Desktop. 
    react-native refetch on focus only
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | // https://github.com/tannerlinsley/react-query/discussions/296#discussioncomment-1244793 | |
| export const useRefetchOnFocus = (refetch = () => {}, canRefetch = true) => { | |
| const [isScreenFocused, setIsScreenFocused] = useState(false); | |
| useFocusEffect(() => { | |
| setIsScreenFocused(true); // when i focus the screen | |
| return () => setIsScreenFocused(false); // when i quit the screen | |
| }); | |
| /* the screen still always active in cache so we need to check that the screen is focused in a use effect | |
| to dispatch the refetch only one time to avoid the infinity loop*/ | |
| useEffect(() => { | |
| if (isScreenFocused && canRefetch) { | |
| refetch(); | |
| } | |
| }, [canRefetch, isScreenFocused, refetch]); | |
| }; | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
Uh oh!
There was an error while loading. Please reload this page.