Last active
October 5, 2020 09:25
-
-
Save sahilrajput03/bf683d83cb6680f5641a1a8fdc6bddc2 to your computer and use it in GitHub Desktop.
A function which helps easying up un mutating state objects when we need to dispatch new unmutated states to `dispatch` calll. # unmutate
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
const getMutable = (state) => JSON.parse(JSON.stringify(state)); // This is doer. | |
const mutableState = getMutable(state); | |
mutableState.books[0].section[2] = 'Things to be learned in august.'; | |
mutableState.books[1].section[4] = 'Things to be learned in november.'; | |
dispatch(mutableState); | |
// ---------------------------------------------------------------------------------------------------------- | |
// Antoher simple approach is using closures like immer.js does(but it does some depth comparisons too), for e.g. below is my | |
// own function `produce` that mimics immerjs's produce: | |
const produce = (immutableData, cb) => { | |
let mutable = JSON.parse(JSON.stringify(immutableData)); | |
cb(mutable); | |
return mutable; | |
}; | |
const data = { | |
a: 1, | |
b: 1 | |
}; | |
const newState = (cb) => produce(data, cb); //This make it super cool to use. Yikes!! | |
// You must import produce from immer.js, like ` import produce from 'immerjs' ` | |
const data2 = produce( | |
data, draft => { | |
draft['a'] = 2; | |
} | |
); | |
const data3 = newState((state) => { //This is essence. | |
state['a'] = 3000; | |
state['b']++; | |
}); | |
console.log("I had ", data); | |
console.log("I have ", data2); | |
console.log("I have ", data3); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment