- The last posts worked with arrays, but there are ways to help enforce state immutability when state is an object. A useful tool for handling objects is the
Object.assign()
Object.assign()
takes a target object and source objects and maps properties from the source objects to the target object. This is used to make shallow copies of objects by passing an empty object as the first argument followed by the object(s) you want to copy.Example:
const myObject = Object.assign({}, obj1, obj2);
This creates
myObject
as a newobject
, which contains the properties that currently exist inobj1
andobj2
.Code:
const defaultState = {
user: 'CamperBot',
status: 'offline',
friends: '732,982',
community: 'freeCodeCamp'
};
const immutableReducer = (state = defaultState, action) => {
switch(action.type) {
case 'ONLINE':
// Don't mutate state here or the tests will fail
return
default:
return state;
}
};
const wakeUp = () => {
return {
type: 'ONLINE'
}
};
const store = Redux.createStore(immutableReducer);
- Here we have a Redux state and actions that were modified to handle our
object
situation. We need to edit the code to return a newstate
object for actions with the typeONLINE
, which set thestatus
property to the stringonline
*Answer:
const defaultState = {
user: 'CamperBot',
status: 'offline',
friends: '732,982',
community: 'freeCodeCamp'
};
const immutableReducer = (state = defaultState, action) => {
switch(action.type) {
case 'ONLINE':
const myObject = Object.assign({}, state, {status: 'online'})
return myObject;
default:
return state;
}
};
const wakeUp = () => {
return {
type: 'ONLINE'
}
};
const store = Redux.createStore(immutableReducer);
Larson, Q., 2019. Frontend Development Libraries. [online] Freecodecamp.org. Available at: https://www.freecodecamp.org/learn/front-end-development-libraries/redux
Top comments (0)