Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-Native Invalid hook call for Flat List Render Item

So i have a react-native flat list where i use hooks in each FlatList renderItem, something like this,

export const RenderEntityList = (props) => {
    const { entityList } = props;
    const getEntityName = useCallBack((entity) => {
        //...get Entity name from list
    }, [entityList]);
    return <FlatList
              data={entityList}
              renderItem={RenderEntity({ getEntityName })}
           />
};


const RenderEntity = (props) => {
    const { getEntityName } = props;
    return (props) => {
        const { item: entity } = props;
        // This is where i get the error Invalid hook call;
        const [entityName, setEntityName] = useState('');
        useEffect(() => {
            setEntityName(getEntityName(entity))
        }, [entity])
        return <ListItem
                  title={entityName}
               />
};

I am not sure what exactly i am doing wrong. Any help on the same would be highly appreciated.

Thanks Regards. Amol

like image 417
Amol Gupta Avatar asked Jun 15 '20 11:06

Amol Gupta


People also ask

How do you fix error invalid hook call Hooks can only be called inside of the body of a function component?

If the error persists, try to delete your node_modules and package-lock. json (not package. json ) files, re-run npm install and restart your IDE. The error is often caused by having multiple versions of react in the same project.

Why Hooks can only be called at the top level of a component?

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.

How do you check you might have mismatching versions of React and the renderer such as React Dom?

Mismatching Versions of React and React DOM You can run npm ls react-dom or npm ls react-native in your application folder to check which version you're using.

What is incorrect about React Hooks?

This could happen for one of the following reasons: You might have mismatching versions of React and the renderer (such as React DOM) You might be breaking the Rules of Hooks. You might have more than one copy of React in the same app See for tips about how to debug and fix this problem.


1 Answers

You are using RenderEntity as function instead of a functional component :

Change this

renderItem={RenderEntity({ getEntityName })}

With :

renderItem={({item, index, separators}) => <RenderEntity item={item} getEntityName={getEntityName}/> }
like image 161
Vivek Doshi Avatar answered Oct 12 '22 12:10

Vivek Doshi