Handling Complex State with createReducer for Multiple Data Streams
Present a more advanced `createReducer` use case that handles state for a dashboard application receiving multiple types of real-time data streams, such as weather and news updates.
import { createReducer } from '@reduxjs/toolkit';
// Define initial state for the dashboard
const initialState = {
weather: {
temperature: null,
condition: ''
},
news: []
};
// Define action types, typically found in a separate file
const UPDATE_WEATHER = 'dashboard/updateWeather';
const RECEIVE_NEWS = 'dashboard/receiveNews';
// Define the createReducer function
const dashboardReducer = createReducer(initialState, {
[UPDATE_WEATHER]: (state, action) => {
// Directly 'mutate' the state thanks to Immer, these are actually applied immutably
state.weather = action.payload;
},
[RECEIVE_NEWS]: (state, action) => {
// Prepend new news items to the list, treating the state as if it were mutable
state.news.unshift(...action.payload);
}
});
export default dashboardReducer;
This is the `dashboardReducer` created with Redux Toolkit's `createReducer` function. It handles two types of actions: updating the weather and receiving news. The `initialState` has a structure to hold data for weather and news. The reducer uses Immer library under the hood, enabling us to write code that seems to mutate the state, but actually produces new immutable state. The `UPDATE_WEATHER` action replaces the weather state with new data, and `RECEIVE_NEWS` appends new news items to the start of the news array.