I am trying to write my first async thunk with the provided function from Redux Toolkit: createAsyncThunk
.
But after hours reading the docs and online instructions, it seems I am missing something as I can't import the action rollDice
.
GenerateRandomDice.spec.ts
import { beforeEach, describe, expect, it } from 'vitest'
import { ReduxStore } from '../../../react-view/main'
import { configureStoreWith } from '../../../app/store'
import { Dependencies } from '../../../app/dependencies'
import { InMemoryIdProvider } from '../../../infrastructure/idProvider/InMemoryIdProvider'
import { InMemoryRandomDiceProvider } from '../../../infrastructure/randomDiceProvider/InMemoryRandomDiceProvider'
describe('Generate Random Dice', () => {
let store: ReduxStore
let dependencies: Dependencies
beforeEach(() => {
dependencies = {
idProvider: new InMemoryIdProvider(),
randomDiceProvider: new InMemoryRandomDiceProvider(),
}
store = configureStoreWith(dependencies)
})
it('should generate 10 random dice', () => {
store.dispatch(rollDice())
const state = store.getState()
expect(state).toBe('something') // I don't expect this to pass, it's not the point
})
})
diceSlice.ts
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import { Dependencies } from '../../app/dependencies'
type ExtraDependencies = {
extra: Dependencies
}
const rollDice = createAsyncThunk<number, any, ExtraDependencies>(
`dice/rollDice`,
async (thunkAPI, { extra: { randomDiceProvider } }) => {
return randomDiceProvider.generateRandomDieValue()
},
)
export const initialState = {
dice: [] as number[],
loading: false,
error: null,
}
export const diceSlice = createSlice({
name: 'dice',
initialState,
reducers: {},
extraReducers: (builder) => {
builder.addCase(rollDice.fulfilled, (state, action) => {
state.dice.push(action.payload)
})
},
})
export const diceReducer = diceSlice.reducer
As far as I understand it, the createSlice
functions should somehow create the action for me, but it's not the case.
What am I missing?