2

I have re-read the documentation a few times and can't seem to figure out an error I'm receiving.

For some reason I need to define the error type in getAccounts and accountsSlice, even though in the documentation it says I shouldn't if I pass rejectValue type and return rejectWithValue(error as ServerError).

interface ServerError {
  statusCode: number
  description: string
}

export const getAccountsSlice = createAsyncThunk<
  GetAccountsState,
  {
    rejectValue: ServerError
  }
>('accountsSlice/getAccounts', async (_, { rejectWithValue }) => {
    try {
      // handle fulfillment
    } catch (error) {
      console.error('REQUEST ERROR --', error)
      return rejectWithValue(error as ServerError)
    }
  }
)

export const accountsSlice = createSlice({
  name: 'accountsSlice',
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(getAccountsSlice.pending, (state) => {
         ...
      })
      .addCase(getAccountsSlice.fulfilled, (state, action) => {
         ...
      })
      .addCase(getAccountsSlice.rejected, (state, action) => {
        return {
          ...state,
          // must add as ServerError or I get an error
          error: action.payload as ServerError,
          isLoading: false
        }
      })
  }
})

In addition, having rejectValue typed in createAysncThunk I get this error when trying to dispatch(getAccounts):

Expected 1 arguments, but got 0.

1 Answer 1

2

You should dispatch(getAccounts()), not dispatch(getAccounts).

For that you need to type the argument as void, and that is also where your error is: Generic arguments are positional - the config object is the third argument and you omitted the second. That way, your getAccounts expected an argument in the form { rejectValue: ServerError }.

You need to type it

export const getAccountsSlice = createAsyncThunk<
  GetAccountsState,
  void,
  {
    rejectValue: ServerError
  }
>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.