I'm having trouble constructing an object. I've got a string (called "SKU" for this example) and it's coming through action
as action.name
.
I have everything available in the reducer function but I need to change the hardcoded SKU
to action.name, but obviously that's not possible in JS. I've tried action.name
, action['name']
and other variations and I'm stuck.
What is the work around? Any help appreciated! Thanks.
Here's some code so you can see what's going on:
function that fires when date changes...
handleChange(date) {
this.props.addDate(date, this.props.dashboardName);
}
mapDispatch which is connected at the bottom of the component export...
const mapDispatchToProps = dispatch => {
return {
addDate: (date, name) => dispatch({
type: 'ACTION_DASHBOARD_ADD_DATE',
date,
name
})
};
};
action creator...
export function DashboardDate() {
return {
type: ACTION_DASHBOARD_ADD_DATE
};
}
case in the switch of the reducer...
case ACTION_DASHBOARD_ADD_DATE: {
var filter = {};
filter[action.name] = action.date;
return {
...state,
dashboard: {
...state.dashboard,
// Below SKU needs to be the value of action.name
SKU: {
// Below too, action.name
...state.dashboard.SKU,
filter
}
}
};
}
I'm not 100% sure where in your code you want to have the sku
appear, but you can create an object with a computed property name like this:
const obj = {
[action.name]: action.payload
};
console.log(obj); // { "sku": "abcd" }
Computed property names are an ES2015 (ES6) feature.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With