Calling useStore inside functional component but getting error

I want to use store data inside of my async action but when I call the useStore hook I get this 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

     export function getCommitsData() {
       const store = useStore();
       return async function (dispatch: Function) {
         try {
           const commits = await axios.get(`url`);
           const commitsData = await commits.data;
    
           dispatch(getCommitsDataAction({ commitsData }));
         } catch (err) {
           await console.log(err);
         }
       };
     }
    

Answer

You are only allowed to use hooks in

  • function components: functions whose name starts with a capital letter which are only used in JSX (they cannot be called directly), or
  • custom hooks: functions whose name starts with use, and to which the same rules apply.

In particular, you are not allowed to use hooks in action creators, which is what you seem to be doing.

If you are using Redux Thunk, I guess you could use getState instead. Alternatively, you could use the useStore hook inside the component and pass the store to the action creator as an argument.