So let's say that I make a REST API call and receive a JSON in this format:
{
"plan": {
"createdDate": "05/04/2017",
"location": {
"city": null
"state": null
}
"family": null
}
}
And within in my reducer, make the JSON as an immutable as so:
Immutable.Map(Immutable.fromJS(action.json))
Along the way, is it possible to add properties under family
?
For instance, when I am submitting a form to a server, ideally I like to send something like this:
{
"plan": {
"createdDate": "05/04/2017",
"location": {
"city": null
"state": null
}
"family": {
"father": "Homer",
"mother": "Marge",
"son": "Bartholomew"
}
}
}
Or do I have to initialized first to have those properties under family
from the start?
So let's say that I make a REST API call and receive a JSON in this format:
{
"plan": {
"createdDate": "05/04/2017",
"location": {
"city": null
"state": null
}
"family": null
}
}
And within in my reducer, make the JSON as an immutable as so:
Immutable.Map(Immutable.fromJS(action.json))
Along the way, is it possible to add properties under family
?
For instance, when I am submitting a form to a server, ideally I like to send something like this:
{
"plan": {
"createdDate": "05/04/2017",
"location": {
"city": null
"state": null
}
"family": {
"father": "Homer",
"mother": "Marge",
"son": "Bartholomew"
}
}
}
Or do I have to initialized first to have those properties under family
from the start?
3 Answers
Reset to default 3You can follow this way via mergeDeep
of Immutable:
const { fromJS } = require('[email protected]')
const initialState = fromJS({
"plan": {
"createdDate": "05/04/2017",
"location": {
"city": null,
"state": null
},
"family": null
}
})
const newState = initialState.mergeDeep({
"plan": {
"family": {
"father": "Homer",
"mother": "Marge",
"son": "Bartholomew"
}
}
})
console.log(newState.toJS())
You will got this result
{
"plan": {
"createdDate": "05/04/2017",
"location": {
"city": null,
"state": null
},
"family": {
"father": "Homer",
"mother": "Marge",
"son": "Bartholomew"
}
}
}
Hope this can help you for solving this same issue with me, I was succeed!
Just to plement @julien-deniau answer. In case you have already properties in your object, you can use mergeIn. For example:
{
"plan": {
"createdDate": "05/04/2017",
"location": {
"city": null
"state": null
}
"family": {
"father": "Homer",
"mother": "Marge",
"son": "Bartholomew"
---> you need to add smthg here
}
}
}
state.mergeIn([
'plan',
'family'], {grandfather:'Abraham Jedediah'});
For the record, you don't need to do
const m = Immutable.Map(Immutable.fromJS(action.json))
But
const m = Immutable.fromJS(action.json)
does the job
Then you can just do:
const n = m.setIn(['plan', 'family'], /* your family object */)
Here :
const n = m.setIn(['plan', 'family'], Immutable.Map({ father: 'Homer', mother: 'Marge', son: 'Bartholomew' }))