Harsh Mishra
Harsh Mishra

Reputation: 978

Error: Invalid hook call. Hooks can only be called inside of the body of a function component in React Native

I am trying to use useSelector within the component still I am getting error saying: Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

backgroundTasks.js:

import axios from "axios";
import AsyncStorage from '@react-native-community/async-storage';
import { baseURL, mlURL } from "../../constants";
import BackgroundFetch from "react-native-background-fetch";
import { useSelector } from "react-redux";
import { showNotification, handleScheduleNotification, handleCancel } from "./notification.android";

const getLatestNotifications = async (headers, user_id) => {
    const Link = `${baseURL}/api/push-notifications`;

    console.log("Push notification Link is", Link);
    try {
        let data = await axios
            .get(
                Link,
                { headers: headers }
            );
        if (data.data.response) {
            console.log("Recieved notification response", data.data.response);
            return data.data.response;
        }
        else {
            return [];
        }
    } catch (err) {
        console.log("Notifications error", err);
        return [];
    }
}

//In startTask I want to use useSeletor but I am getting error.

const startTask = async (task = "notifications") => {
    console.log("Background task started");
    console.log('background');
    const token = await AsyncStorage.getItem("token");
    const user_id = await AsyncStorage.getItem("user_id");
    const userName = await AsyncStorage.getItem("name");
    const notificationsUnReadNumber = useSelector((state) => state.notification.notificationCount); //Here
        console.log(notificationsUnReadNumber);
    const apiHeaders = {
        'x-access-token': token,
        'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:84.0) Gecko/20100101 Firefox/84.0',
        'Accept': 'application/json, text/plain, */*',
    };
    if (task == "notifications" && token) {
        let notifications = await getLatestNotifications(apiHeaders, user_id);
        console.log("Get Latest Notifications data", notifications);
        if (notifications && notifications.length > 0 && notificationsUnReadNumber !==0) {
            console.log('inside notification');
            notifications.forEach((notification) => {
                showNotification(notification.title, notification.content, String(notification._id));
            });
        }

    }

};

const inititalizeBackgroundTasks = async () => {
    const onEvent = async (taskId) => {    //This task will run when app is not terminated (foreground/background)
        console.log('[BackgroundFetch] task: ', taskId);
        // Do your background work...
        console.log("Task background called")
        console.log("Received background-fetch event: ", taskId);
        startTask("notifications");
        BackgroundFetch.finish(taskId);
    }

    // Timeout callback is executed when your Task has exceeded its allowed running-time.
    // You must stop what you're doing immediately BackgorundFetch.finish(taskId)
    const onTimeout = async (taskId) => {
        console.warn('[BackgroundFetch] TIMEOUT task: ', taskId);
        BackgroundFetch.finish(taskId);
    }


    let status = await BackgroundFetch.configure({
        minimumFetchInterval: 15,     //Run Task every 15 minutes
        // Android options
        forceAlarmManager: true,     // <-- Set true to bypass JobScheduler.
        stopOnTerminate: false,
        startOnBoot: true,
        enableHeadless: true,
        requiredNetworkType: BackgroundFetch.NETWORK_TYPE_NONE, // Default
        requiresCharging: false,      // Default
        requiresDeviceIdle: false,    // Default
        requiresBatteryNotLow: false, // Default
        requiresStorageNotLow: false  // Default
    }, onEvent, onTimeout);

    console.log('[BackgroundFetch] configure status: ', status);

};

export { inititalizeBackgroundTasks};

If I have to make this a component then How can I export backgroundTasks as default and export {inititalizeBackgroundTasks} as normal?

I want to export only one component which is inititalizeBackgroundTasks and use others as a function inside my component so how can I use useSelector if I am doing it in the wrong way?

Upvotes: 3

Views: 8147

Answers (2)

Morta
Morta

Reputation: 399

Only Call Hooks from React Functions
✅ Call Hooks from React function components.
✅ Call Hooks from custom Hooks

Learn more about Rules of Hooks in the documentation.
I hope this work around helps you (as you mentioned above) we create backgroundTasks export default as a functional component so we can use react hooks.

import { useEffect } from "react";
import axios from "axios";
import AsyncStorage from "@react-native-community/async-storage";
import { baseURL, mlURL } from "../../constants";
import BackgroundFetch from "react-native-background-fetch";
import { useSelector } from "react-redux";
import {
  showNotification,
  handleScheduleNotification,
  handleCancel,
} from "./notification.android";

const getLatestNotifications = async (headers, user_id) => {
  const Link = `${baseURL}/api/push-notifications`;

  console.log("Push notification Link is", Link);
  try {
    let data = await axios.get(Link, { headers: headers });
    if (data.data.response) {
      console.log("Recieved notification response", data.data.response);
      return data.data.response;
    } else {
      return [];
    }
  } catch (err) {
    console.log("Notifications error", err);
    return [];
  }
};

//In startTask I want to use useSeletor but I am getting error.

const startTask = async (task = "notifications", notificationsUnReadNumber) => {
  console.log("Background task started");
  console.log("background");
  const token = await AsyncStorage.getItem("token");
  const user_id = await AsyncStorage.getItem("user_id");
  const userName = await AsyncStorage.getItem("name");
  console.log(notificationsUnReadNumber);
  const apiHeaders = {
    "x-access-token": token,
    "User-Agent":
      "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:84.0) Gecko/20100101 Firefox/84.0",
    Accept: "application/json, text/plain, */*",
  };
  if (task == "notifications" && token) {
    let notifications = await getLatestNotifications(apiHeaders, user_id);
    console.log("Get Latest Notifications data", notifications);
    if (
      notifications &&
      notifications.length > 0 &&
      notificationsUnReadNumber !== 0
    ) {
      console.log("inside notification");
      notifications.forEach((notification) => {
        showNotification(
          notification.title,
          notification.content,
          String(notification._id)
        );
      });
    }
  }
};

export const inititalizeBackgroundTasks = async (notificationsUnReadNumber) => {
  let status = await BackgroundFetch.configure(
    {
      minimumFetchInterval: 15, //Run Task every 15 minutes
      // Android options
      forceAlarmManager: true, // <-- Set true to bypass JobScheduler.
      stopOnTerminate: false,
      startOnBoot: true,
      enableHeadless: true,
      requiredNetworkType: BackgroundFetch.NETWORK_TYPE_NONE, // Default
      requiresCharging: false, // Default
      requiresDeviceIdle: false, // Default
      requiresBatteryNotLow: false, // Default
      requiresStorageNotLow: false, // Default
    },
    async (taskId) => {
      //This task will run when app is not terminated (foreground/background)
      console.log("[BackgroundFetch] task: ", taskId);
      // Do your background work...
      console.log("Task background called");
      console.log("Received background-fetch event: ", taskId);
      startTask("notifications", notificationsUnReadNumber);
      BackgroundFetch.finish(taskId);
    },
    // Timeout callback is executed when your Task has exceeded its allowed running-time.
    // You must stop what you're doing immediately BackgorundFetch.finish(taskId)
    async (taskId) => {
      console.warn("[BackgroundFetch] TIMEOUT task: ", taskId);
      BackgroundFetch.finish(taskId);
    }
  );

  console.log("[BackgroundFetch] configure status: ", status);
};

const backgroundTasks = () => {
  const notificationsUnReadNumber = useSelector(
    (state) => state.notification.notificationCount
  ); //Here

  useEffect(() => {
    if (notificationsUnReadNumber) {
      inititalizeBackgroundTasks(notificationsUnReadNumber);
    }
  }, [notificationsUnReadNumber]);
};

export default backgroundTasks;

Upvotes: 3

import the useSelector in the component where you call startTask() and add it as the second parameter like startTask('notifications', useSelector). This should solve your problem.

Upvotes: 0

Related Questions