1

I've created a typed AsyncThunk following the instructions from the redux-toolkit docs. It consists in a method to get data from an API, without any filters and return as a typed array. The code in this AsyncThunk also calls a function to show the loading progress of data and I'm trying to use the ThunkApi config to get a reference to dispatch and call this function.

I'm doing this way:

deviceOperations.ts

import { createAsyncThunk } from '@reduxjs/toolkit';
import { AppDispatch } from 'src/store';
import { loaderActions } from '../../../features/loader/redux';
import deviceManager from '../deviceManager';

export const getAllDevices = createAsyncThunk<
  Device[],
  {
    dispatch: AppDispatch;
  }
>('device/GET_ALL_DEVICES', async (thunkApi) => {
  thunkApi.dispatch(loaderActions.start('getAllDevices'));
  try {
    const devices = await deviceManager.getAllDevices();
    return { ...devices };
  } finally {
    thunkApi.dispatch(loaderActions.stop('getAllDevices'));
  }
});

DevicePage.tsx

const DevicePage = () => {
  const classes = useStyles();
  const dispatch = useAppDispatch();
  const { push } = useHistory();

  useEffect(() => {
    dispatch(deviceOperations.getAllDevices());
  }, [dispatch]);
};

The line dispatch(deviceOperations.getAllDevices()); is causing the error Expected 1 arguments, but got 0.ts(2554) typings.d.ts(302, 701): An argument for 'arg' was not provided..

What is wrong with this function?

juliano.net
  • 7,982
  • 13
  • 70
  • 164

1 Answers1

1

The AsyncThunkPayloadCreator expects you to declare at least one argument I believe. In the example in the doc it's userId of type number for example.

In your case, you don't want to pass an arg, but you still have to declare a void argument. Just modify your getAllDevices function declaration to this:


import { createAsyncThunk } from '@reduxjs/toolkit';
import { AppDispatch } from 'src/store';
import { loaderActions } from '../../../features/loader/redux';
import deviceManager from '../deviceManager';

// notice the empty arg _. You could type it with `void`
export const getAllDevices = createAsyncThunk('device/GET_ALL_DEVICES', async (_, thunkApi) => {
  thunkApi.dispatch(loaderActions.start('getAllDevices'));
  try {
    const devices = await deviceManager.getAllDevices();
    return { ...devices };
  } finally {
    thunkApi.dispatch(loaderActions.stop('getAllDevices'));
  }
});

HHK
  • 1,352
  • 1
  • 15
  • 25