Blog>
Snippets

Serializing and Deserializing Actions

Showcase how to implement a pattern for serializing and deserializing actions to ensure that they can be safely transmitted over the network or stored.
class Action { 
    constructor(type, payload) {
        this.type = type;
        this.payload = payload;
    }
    // Serialize the action into a JSON string
    serialize() {
        return JSON.stringify({ type: this.type, payload: this.payload });
    }
    // Deserialize the JSON string back into an action
    static deserialize(serializedAction) {
        const { type, payload } = JSON.parse(serializedAction);
        return new Action(type, payload);
    }
}

// Example usage:
// Serialize an action
const action = new Action('ADD_TODO', { text: 'Learn serialization' });
const serializedAction = action.serialize();

// Deserialize the action
const deserializedAction = Action.deserialize(serializedAction);
This example defines an Action class with a constructor to hold type and payload, a serialize method to convert the action into a JSON string, and a static deserialize method to convert the JSON string back into an Action object. An action is created, serialized, and then deserialized as an example usage.