0

I'm trying to make a thunk that filters a base array and passes data into the filtered array, but I keep getting an error when I do a dispatch in useEffect.

Writes: "Argument of type '(dispatch: ThunkDispatch<IRootState, void, Action>, getState: IRootState) => void' is not assignable to parameter of type 'AnyAction'."

I don't understand what to do, I followed the redux documentation, but still nothing works

Thunk action-creator:

export const filterServices = () => {
  return (
    dispatch: ThunkDispatch<IRootState, void, Action>,
    getState: IRootState
  ) => {
    const category = getState.filters.category;
    const subcategory = getState.filters.subcategory;
    let result = getState.services.services;

    result =
      category === 'All categories'
        ? result
        : result.map((e: any) => e.category === category);
    result =
       subcategory === 'All Subcategories'
        ? result
        : result.map((e: any) => e.subcategory === subcategory);

    dispatch(getfilteringServices(result));
  };
};

Action interfaces

export interface IFilteringServices {
  type: ActionType.FILTERING_SERVICES;
  payload: IService[];
}


export type Action =
  | IGetServices
  | IAddToCart
  | IRemoveFromCart
  | IFilteringServices
  | IUseFilters;

RootState interface:

export type IRootState = typeof storeState;

dispatch

useEffect(() => {
    dispatch(filterServices());
  }, []);
Dmitry Staver
  • 139
  • 1
  • 2
  • 8
  • I'd recommend to use redux-toolkit and follow their docs on setting up a `useAppDispatch` hook instead of the default one, it has much better TS support to deal with cases like this one. Same for `useAppSelector`, no more need to explicitly type everything. – timotgl Jun 09 '22 at 13:29
  • I cannot use the redux toolkit – Dmitry Staver Jun 09 '22 at 13:41
  • 1
    That's a shame, but also this question has been answered before: https://stackoverflow.com/questions/64857870/how-to-dispatch-thunkaction-with-redux-thunk-and-typescript `getState: IRootState` is wrong btw, it's a function that returns the state, not the state itself. – timotgl Jun 09 '22 at 14:03
  • Now a lot of jobs require knowledge of the old redux, I have already learned redux toolkit and Mobx, so I decided to make a new project entirely on the old Redux, preparing for interviews. Thank you, your link helped, it had the right solution there – Dmitry Staver Jun 09 '22 at 14:36

1 Answers1

1

I changed the dispach hook and everything started working:

export const useAppDispatch = () =>
  useDispatch<ThunkDispatch<IRootState, unknown, AnyAction>>();

Also changed the getState call, I forgot it was a function:

(dispatch: Dispatch<Action>, getState: () => IRootState) => {

const state = getState().services.filteredServices

...other code
}


I changed this code with filtering, but maybe the information about the hook and getState will help someone

Dmitry Staver
  • 139
  • 1
  • 2
  • 8