Home > database >  Invalid Hook Call when calling a helper function with useSelector
Invalid Hook Call when calling a helper function with useSelector

Time:03-29

I created a helper function (fetchBatchInfo) inside a TypeScript file to use in more than one component but it is returning the error "Invalid Hook Call when calling a function with useSelector" since it has a useSelector inside. I'm using the function renderBatches that calls this helper function inside a FlatList renderItem. I tried searching for alternatives and found about custom hooks, but I could not find a way to execute the custom hook inside the render function of the FlatList, since it is still a hook.

I'm still a beginner in redux, is there a way to achieve what I'm trying to?

Render function of flatlist:

const renderBatches = useCallback((animalBatch: AnimalBatch) => {
    let animalBatch: AnimalBatch= animalBatch.item;

    let { chickenBatch } = fetchBatchInfo(animalBatch);

    return (
        <Text>{animalBatch.quantity} - {chickenBatch.sex}</Text>
    );
}, [animalBatchUser]);

Helper function that returns all data of current animalBatch:
export const fetchBatchInfo = (animalBatch: AnimalBatch) => {
    const chickenBatchesUser = useSelector(
        (state: RootStateOrAny) => state.batch.chickenBatchesUser);

    let chickenBatch: ChickenBatch | undefined = chickenBatchesUser.find(
        (chickenBatch: ChickenBatch) => chickenBatch.idChickenBatch == animalBatch.idChickenBatch)

    return {
        chickenBatch
    };
}

Before using this helper function, it was working, because the chickenBatchesUser useSelector was outside the render function, but since I will be using this code in other places I want to make this helper function work.

Does someone know a way to do this?

CodePudding user response:

// your fetch must be defined as a hook, to be inlcuded into the react lifecylce, and hooks starts with useXXX();

export const useChickenBatch = (animalBatch: AnimalBatch) => {
    const chickenBatchesUser = useSelector(
        (state: RootStateOrAny) => state.batch.chickenBatchesUser);

    let chickenBatch: ChickenBatch | undefined = chickenBatchesUser.find(
        (chickenBatch: ChickenBatch) => chickenBatch.idChickenBatch == animalBatch.idChickenBatch)

    return { chickenBatch };
}

//inside your component
const YourComponent = ({ animalBatch }) => {
  let { chickenBatch } = useChickenBatch(animalBatch);  
  return (
    <Text>{animalBatch.quantity} - {chickenBatch.sex}</Text>
  );
};

Read here about the hooks-rules: https://reactjs.org/docs/hooks-rules.html

  • Related