Blog>
Snippets

Basic Real-Time Reducer with createReducer

Show how to use `createReducer` to create a simple reducer that can handle real-time updates to a chat application's messages state.
import { createReducer } from '@reduxjs/toolkit';

// Action types
const MESSAGE_RECEIVED = 'chat/MESSAGE_RECEIVED';
const MESSAGE_SENT = 'chat/MESSAGE_SENT';

// Initial state for the chat messages
const initialState = {
  messages: []
};

// Reducer function using createReducer
const chatReducer = createReducer(initialState, {
  [MESSAGE_RECEIVED]: (state, action) => {
    // Appends received message to the messages array
    state.messages.push(action.payload);
  },
  [MESSAGE_SENT]: (state, action) => {
    // Appends sent message to the messages array
    state.messages.push(action.payload);
  }
});

export default chatReducer;
This code defines a reducer for a chat application using the createReducer utility from Redux Toolkit. It handles two types of actions: MESSAGE_RECEIVED and MESSAGE_SENT, both updating the state by appending a new message to the 'messages' array.
// Example usage of the chatReducer
import { createStore } from 'redux';
import chatReducer from './chatReducer';

// Create a Redux store holding the state of your app.
// Its API is { subscribe, dispatch, getState }.
let store = createStore(chatReducer);

// Dispatch actions to test the reducer
store.dispatch({
  type: MESSAGE_RECEIVED,
  payload: { author: 'Alice', text: 'Hello!' }
});

store.dispatch({
  type: MESSAGE_SENT,
  payload: { author: 'Bob', text: 'Hi, Alice!' }
});

// Log the initial state
console.log('Initial state:', store.getState());

// The subscribed handler will be executed on every state change
store.subscribe(() => console.log('Updated state:', store.getState()));
This additional code snippet is an example showing how to create a Redux store with the chatReducer, dispatch actions to simulate sending and receiving messages, and subscribe to the store updates to log them to the console.