Redux Toolkit now has a createListenerMiddleware.
A Redux middleware that lets you define "listener" entries that
contain an "effect" callback with additional logic, and a way to
specify when that callback should run based on dispatched actions or
state changes.
It's intended to be a lightweight alternative to more widely used
Redux async middleware like sagas and observables.
See https://redux-toolkit.js.org/api/createListenerMiddleware
Example of how to dispatch an action in response to a failed api call using createListenerMiddleware
from @reduxjs/toolkit
:
// Create a new file src/app/ListenerMiddleware.ts with this content.
import { createListenerMiddleware } from '@reduxjs/toolkit'
export const listenerMiddleware = createListenerMiddleware()
// Add the listenerMiddleware in src/app/store.ts
import { listenerMiddleware } from './ListenerMiddleware';
const store = configureStore({
// Existing code omitted. Add the line below.
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().prepend(listenerMiddleware.middleware),
})
// In your slice file as src/features/user/UserSlice.ts
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { listenerMiddleware } from '../../app/ListenerMiddleware';
export const userSlice = createSlice({
name: 'user',
// initial state, reducers and extraReducers
})
// exports code omitted.
export const fetchSomeApi = createAsyncThunk('user/fetchSomeApi', async () => {
// Make an api call and return response data.
})
const someCodeWithSideEffects = createAsyncThunk('user/someCodeWithSideEffects', async (youCanPassData: string) => {
// Code to run if fetchSomeApi was rejected.
})
// Use listenerMiddleware to subscribe to the fetchSomeApi.rejected action and dispatch another action.
listenerMiddleware.startListening({
actionCreator: fetchSomeApi.rejected,
effect: async (action, listenerApi) => {
const payload = action.payload
await listenerApi.dispatch(someCodeWithSideEffects('some input'));
},
})
AudioElement
? It seems like that shouldn't be something in state. – Dabney