Using hooks inside helper functions

Viewed 973

I have function like below

import React from "react";
import { useSelector, useDispatch } from "react-redux";

export const getCat = () => {
  const lang = useSelector((state) => state.main.language);
  return fetch("https://example.co/get/cat.php?lang="+lang, {
    method: "GET",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
    },
  })
    .then((response) => response.json())
    .then((responseData) => {
      return responseData;
    })
    .catch((error) => console.warn(error));
};

I want to access the state value using useselector and pass it to my url.but I am getting following error

    Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app

But I have other files like below and it works fine.

const Lang = () => {
  const lang = useSelector((state) => state.main.language);
  console.log("lang--" + lang);
};
export default Lang;
1 Answers

You can't use hooks inside helper functions because React is not in scope in a helper function that gets called directly. Keep in mind that just importing React and the hook functions don't bring React in scope. Even though React function components are just functions they get handled and called from within the React framework, which is different than calling a helper function directly such as what you would be doing for getCat().

To access state from inside a helper function you directly call you have a few choices:

Pass a variable to the function that represents your state

const getCat = state => {
   const lang = state.main.language;
   ...
}

Pass state values in independently

const getCat = lang => {
    ...
}

Pass a function delegate to your helper function that is able to access state from within the component that calls your helper function

const getCat = stateFunc => {
    const lang = stateFunc();
    ...
}

This is all good if you just need to read state, but as with any state variable be cautious of how you change any values.

Related