Home > Blockchain >  how to use netinfo inside reducer or custom function
how to use netinfo inside reducer or custom function

Time:06-04

I'm making an offline-first app with react-native, expo and redux, I need to send the user changes back to the server depending on the internet connection, so I'm using expo-background-fetch to get this task done periodically with a custom function or dispatching some action that use netInfo to check the internet connection as a condition to do the job, but it doesn't work since always says that "Error: Invalid hook call. Hooks can only be called inside of the body of a function component" either in reducer or in the custom function.

import * as BackgroundFetch from 'expo-background-fetch';
import * as TaskManager from 'expo-task-manager';
import {sync} from './sync';
const BACKGROUND_FETCH_TASK = 'background-fetch';

TaskManager.defineTask(BACKGROUND_FETCH_TASK, async () => {
    const now = Date.now();
  
    console.log(`Got background fetch call at date: ${new Date(now).toISOString()}`);
    sync();
    // Be sure to return the successful result type!
    return BackgroundFetch.BackgroundFetchResult.NewData;
});

async function registerBackgroundFetchAsync() {
    console.log('registered');
    return BackgroundFetch.registerTaskAsync(BACKGROUND_FETCH_TASK, {
      minimumInterval: 1, // 15 minutes
      stopOnTerminate: false, // android only,
      startOnBoot: true, // android only
    });
}

this is on the App.js file on the global scope, then on the component I registered the task with await registerBackgroundFetchAsync(); and my sync.js file looks like this:

import {useNetInfo} from "@react-native-community/netinfo";

export function sync () {
    const netInfo = useNetInfo();
}

any solution or workaround?

CodePudding user response:

It looks like you shouldn't be calling sync in your defineTask callback. useNetInfo is meant to be called from within a React function component. You can use the other methods that aren't hooks. https://github.com/react-native-netinfo/react-native-netinfo#fetch is probably your friend.

  • Related