Using ES6 Destructuring in Redux Reducers
Demonstrate how to simplify the reducer's code by utilizing ES6 destructuring to extract data from action payloads.
const initialState = {
user: null,
posts: [],
};
function userReducer(state = initialState, action) {
// Destructure type and payload from action
const { type, payload } = action;
switch (type) {
case 'SET_USER':
// Destructure user data from payload for SET_USER action
const { user } = payload;
return {
...state,
user,
};
case 'ADD_POST':
// Destructure post data from payload for ADD_POST action
const { post } = payload;
return {
...state,
posts: [...state.posts, post],
};
// Other action cases
default:
return state;
}
}
This code sets up a Redux reducer for a fictitious application state consisting of a user object and an array of posts. The reducer uses ES6 destructuring to simplify extracting the 'type' and 'payload' properties from the action parameter. For specific actions like 'SET_USER' and 'ADD_POST', it further destructures to get 'user' and 'post' data respectively from the 'payload'. This approach keeps the reducer functions clean and readable.