Axel
Axel

Reputation: 5111

Typescript throws error when returning array of data in redux createAsyncThunk

So I am using the following code to fetch list of users,

export const fetchUserById = createAsyncThunk(
  "users/fetchById",
  async (_, { rejectWithValue, fulfillWithValue }) => {
    try {
      const response = await fetch(`https://reqres.in/api/users`)
      const j = (await response.json()) as MyData[]
      return fulfillWithValue(j)
    } catch (e) {
      return rejectWithValue(e.response)
    }
  }
)

Typescript gives following error,

Argument of type '(_: void, { rejectWithValue, fulfillWithValue }: GetThunkAPI<{}>) => Promise<RejectWithValue<unknown, unknown> | FulfillWithMeta<MyData[], unknown>>' is not assignable to parameter of type 'AsyncThunkPayloadCreator<MyData[], void, {}>'.
  Type 'Promise<RejectWithValue<unknown, unknown> | FulfillWithMeta<MyData[], unknown>>' is not assignable to type 'AsyncThunkPayloadCreatorReturnValue<MyData[], {}>'.
    Type 'Promise<RejectWithValue<unknown, unknown> | FulfillWithMeta<MyData[], unknown>>' is not assignable to type 'Promise<RejectWithValue<unknown, unknown> | MyData[]>'.
      Type 'RejectWithValue<unknown, unknown> | FulfillWithMeta<MyData[], unknown>' is not assignable to type 'RejectWithValue<unknown, unknown> | MyData[]'.
        Type 'FulfillWithMeta<MyData[], unknown>' is not assignable to type 'RejectWithValue<unknown, unknown> | MyData[]'.
          Type 'FulfillWithMeta<MyData[], unknown>' is not assignable to type 'RejectWithValue<unknown, unknown>'.
            Types have separate declarations of a private property '_type'.ts(2345)

Upvotes: 0

Views: 2754

Answers (1)

Lin Du
Lin Du

Reputation: 102207

Give a type for fulfillWithValue property of ThunkApiConfig generic parameter.

import { createAsyncThunk } from '@reduxjs/toolkit';

interface MyData {}

export const fetchUserById = createAsyncThunk<MyData[], void, { fulfilledMeta: any }>(
  'users/fetchById',
  async (_, { rejectWithValue, fulfillWithValue }) => {
    try {
      const response = await fetch(`https://reqres.in/api/users`);
      const j = await response.json();
      return fulfillWithValue(j, null);
    } catch (e) {
      return rejectWithValue(e.response);
    }
  },
);

package version: "@reduxjs/toolkit": "^1.6.0"

Reference source code

Upvotes: 1

Related Questions