react-nativeredux-saga

Enter data offline and automatically call api to update data to database


I want to store data offline when the internet is not connected and after the internet is connected, it automatically updates the data to a database through API. How can I do that with react native, NetInfo redux-saga, or any other solutions for this case? Many thanks


Solution

  • From detecting connection, you can use this library

    @react-native-community/netinfo
    

    You need to create global component for showing the internet connection (maybe ModalNetworkError). Inside that component, you should handle the internet connection at use effect, like this. And when there is not internet connection, you will update your reducer. And when user has internet connection, call the api. Maybe u need to store the last api call too.

    useEffect(() => {
        const unsubscribe = NetInfo.addEventListener((state) => {
          if (state.type === 'unknown') {
            setShowModal(false)
          } else if (state.isConnected && state.isInternetReachable) {
            setShowModal(false)
            // call api here
          } else if (state.type !== '' && state.isConnected && !state.isInternetReachable) {
            setShowModal(false)
            // update your reducer here
          } else {
            setShowModal(true)
          }
        })
    
        return () => {
          unsubscribe()
        }
     }, [showModal, dispatch])
    

    Because I am using react hooks, I put this global component inside my routes js. Like this,

    <NavigationContainer linking={linking}>
      <RootStackScreen guest={guest} welcome={welcome} userToken={userToken} />
      <ModalNetworkError />
    </NavigationContainer>