Created
August 29, 2019 16:24
-
-
Save neves/48e58602c6a0ba551f7e881720929721 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import produce from 'immer' | |
const state = { | |
activeUserId: 123, | |
activeSessionIndex: 0, | |
sessions: { | |
123: [ | |
{ | |
products: [{ id: 456, name: 'iPhone' }] | |
} | |
] | |
} | |
} | |
function log(data) { | |
console.log(JSON.stringify(data, null, 2)) | |
} | |
function addItem(currentState, item) { | |
return produce(currentState, s => { | |
s.sessions[s.activeUserId][s.activeSessionIndex].products.push(item) | |
}) | |
} | |
log(state) | |
log(addItem(state, { id: 789, name: 'iPad' })) | |
/* | |
{ | |
"activeUserId": 123, | |
"activeSessionIndex": 0, | |
"sessions": { | |
"123": [ | |
{ | |
"products": [ | |
{ | |
"id": 456, | |
"name": "iPhone" | |
} | |
] | |
} | |
] | |
} | |
} | |
index.js:28 { | |
"activeUserId": 123, | |
"activeSessionIndex": 0, | |
"sessions": { | |
"123": [ | |
{ | |
"products": [ | |
{ | |
"id": 456, | |
"name": "iPhone" | |
}, | |
{ | |
"id": 789, | |
"name": "iPad" | |
} | |
] | |
} | |
] | |
} | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment