Meta Fields: Adding Timestamps, IDs, or Metadata
What you'll learn: How to enrich action objects with extra information like timestamps or IDs for debugging, logging, and tracking.
Beyond Type and Payload
So far, your action objects have contained type (what happened) and payload (the data). But sometimes you need additional metadata about when or why an action occurred. Think of it like adding a postmark to a letter—it's not the message itself, but useful information about the message.
Common Meta Fields
You can extend action objects with a meta property to store:
- Timestamps: When the action was dispatched
- Request IDs: Correlation IDs for tracking async operations
- User context: Who triggered the action
- Debug info: Stack traces, component names, etc.
type Action =
| {
type: 'ADD_ITEM';
payload: { id: string; name: string };
meta: { timestamp: number; requestId: string };
}
| {
type: 'REMOVE_ITEM';
payload: { id: string };
meta: { timestamp: number };
};
Action Creator with Metadata
function addItem(name: string) {
return {
type: 'ADD_ITEM' as const,
payload: {
id: crypto.randomUUID(),
name
},
meta: {
timestamp: Date.now(),
requestId: crypto.randomUUID()
}
};
}
Your reducer typically ignores the meta field—it doesn't affect state transitions. But logging middleware, debugging tools, or audit trails can read it:
function reducer(state: State, action: Action): State {
console.log(`Action ${action.type} at ${action.meta.timestamp}`);
// Process action normally...
}
When to Use Meta Fields
- Debugging: Track which component dispatched an action
- Analytics: Record when users perform actions
- Request correlation: Link actions to API calls
- Undo/redo systems: Store original timestamps
Key Takeaway: Meta fields let you attach debugging and tracking information to actions without cluttering your reducer logic—the reducer processes type and payload, while tools consume meta.