Skip to content

Instantly share code, notes, and snippets.

@neves
Created August 29, 2019 16:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neves/48e58602c6a0ba551f7e881720929721 to your computer and use it in GitHub Desktop.
Save neves/48e58602c6a0ba551f7e881720929721 to your computer and use it in GitHub Desktop.
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