Reputation: 1659
I have a packageReducer which keeps the packageType and packageList related details. once the details are fetched from the server I need to replace the initial state values with the new values that are been fetched. As an example, if the packageLists are been fetched I need to replace only the "packageList"
Below is my PackageState reducer,
const initialState = {
packageList: packageListInitialState,
packageTypes: [{title: 'Select Package Type', value: ''}],
};
export default function packageState( state = initialState, action ) {
switch ( action.type ) {
case FETCH_PACKAGE_LIST_SUCCESS:{
return Object.assign( {}, state, action.payload );
}
case FETCH_PACKAGE_TYPES_SUCCESS:{
return Object.assign( {}, state, action.payload );
}
default:
return state;
}
}
The way I have implemented I think im replacing the entire state, Can someone let me know how I can achieve it?
Thank you.
Upvotes: 1
Views: 2924
Reputation: 9701
You are not:
var state = {a: 1, b: 2, c: 3}
var newData = {a: 4, b: 5}
console.log(Object.assign( {}, state, newData )) // { a: 4, b: 5, c: 3 }
Properties in the target object will be overwritten by properties in the sources if they have the same key. Later sources' properties will similarly overwrite earlier ones. (docs)
So, as long as your payload contains the keys that you really want to update, you are safe. You can also do it in a simpler way if you use ES6's spread syntax (I'm assuming your payload looks like {packageList: data}
):
const initialState = {
packageList: packageListInitialState,
packageTypes: [{title: 'Select Package Type', value: ''}],
};
export default function packageState( state = initialState, action ) {
switch ( action.type ) {
case FETCH_PACKAGE_LIST_SUCCESS:{
return {...state, ...action.payload};
}
case FETCH_PACKAGE_SETTINGS_SUCCESS:{
return {...state, ...action.payload};
}
default:
return state;
}
}
Upvotes: 1
Reputation: 6360
Under the assumption that the action you're trying to achieve this in is only the FETCH_PACKAGE_LIST_SUCCESS
action, and the payload is the updated/fetched list, then you just need to return an object as shown below.
Since you're trying to return an object with only one of the two properties changed, then you can use the previous state's value for the unchanged property and update the other.
const initialState = {
packageList: packageListInitialState,
packageTypes: [{title: 'Select Package Type', value: ''}],
};
export default function packageState( state = initialState, action ) {
switch ( action.type ) {
case FETCH_PACKAGE_LIST_SUCCESS:{
return { packageList: action.payload, packageTypes: state.packageTypes }
}
case FETCH_PACKAGE_SETTINGS_SUCCESS:{
return Object.assign( {}, state, action.payload );
}
default:
return state;
}
}
Upvotes: 0