Home > Back-end >  I can't do dispatch inside useEffect - React Redux Typescript
I can't do dispatch inside useEffect - React Redux Typescript

Time:10-12

I need to make the dispatch inside the useEffect but I get the following error:

Uncaught Error: Invalid hook call. Hooks can only be called inside the body of a function component. This can happen for one of the following reasons

  1. You may have versions of React and the renderer (such as React DOM) that don't match.
  2. You could be breaking hook rules.
  3. You may have more than one copy of React in the same application. See https://reactjs.org/link/invalid-hook-call for tips on how to debug and fix this problem.

If I remove the dispatch outside of the useEffect, no error pops. I don't know how to fix this as when I have done something similar in JS I have not had the same thing happen. Any suggestions on how to fix it?

My component:

import { useEffect } from "react";
import { fetchGetPosts } from "../features/thunks/fetchGetPosts";
import { useAppDispatch, useAppSelector } from "../hooks/redux-hooks";
import { GridCard } from "./GridCard";

export const Grid = () => {

  const dispatch = useAppDispatch;

  const postsList = useAppSelector((state) => state.posts.posts);

   useEffect(() => {
     dispatch(fetchGetPosts());
   }, [dispatch]);


  return (
    <>
      <div className="grid">
        <div className="grid__container">
          <GridCard />
        </div>
      </div>
    </>
  );
};

redux-hooks.ts:

import { AsyncThunkAction } from "@reduxjs/toolkit";
import { useSelector, useDispatch, TypedUseSelectorHook } from "react-redux";
import { AppDispatch, RootState } from "../store/store";

export const useAppDispatch = (arg: AsyncThunkAction<void, void, {}>) => useDispatch<AppDispatch>();
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;

store.ts:

import { configureStore } from "@reduxjs/toolkit";
import postsSlice from "../features/postsSlice";

export const store = configureStore({
  reducer: {
    posts: postsSlice,
  },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({ serializableCheck: false }),
});

export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;

CodePudding user response:

As you can see

export const useAppDispatch = (arg: AsyncThunkAction<void, void, {}>) => useDispatch<AppDispatch>();

useAppDispatch is a function

So you have to do

const dispatch = useAppDispatch();
  • Related