firebase login
firebase init
firebase deploy
Teens to Learn Programming with Shuyan
- function updateNestedState(state, action) {
- let nestedState = state.nestedState;
- // ERROR: this directly modifies the existing object reference - don't do this!
- nestedState.nestedField = action.data;
- return {
- ...state,
- nestedState
- };
- }
nestedState
variable was still pointing at the existing object, the state was directly mutated.
- function updateNestedState(state, action) {
- // Problem: this only does a shallow copy!
- let newState = {...state};
- // ERROR: nestedState is still the same object!
- newState.nestedState.nestedField = action.data;
- return newState;
- }
nestedState
object should be copied as well.state.first.second[someId].fourth
might look like:
- function updateVeryNestedField(state, action) {
- return {
- ...state,
- first : {
- ...state.first,
- second : {
- ...state.first.second,
- [action.someId] : {
- ...state.first.second[action.someId],
- fourth : action.someValue
- }
- }
- }
- }
- }
push
, unshift
, and splice
. Since we don't want to mutate state directly in reducers, those should normally be avoided. Because of that, you might see "insert" or "remove" behavior written like this:
- function insertItem(array, action) {
- return [
- ...array.slice(0, action.index),
- action.item,
- ...array.slice(action.index)
- ]
- }
- function removeItem(array, action) {
- return [
- ...array.slice(0, action.index),
- ...array.slice(action.index + 1)
- ];
- }
- function insertItem(array, action) {
- let newArray = array.slice();
- newArray.splice(action.index, 0, action.item);
- return newArray;
- }
- function removeItem(array, action) {
- let newArray = array.slice();
- newArray.splice(action.index, 1);
- return newArray;
- }
- function removeItem(array, action) {
- return array.filter( (item, index) => index !== action.index);
- }
Array.map
, returning a new value for the item we want to update, and returning the existing values for all other items:
- function updateObjectInArray(array, action) {
- return array.map( (item, index) => {
- if(index !== action.index) {
- // This isn't the item we care about - keep it as-is
- return item;
- }
- // Otherwise, this is the one we want - return an updated value
- return {
- ...item,
- ...action.item
- };
- });
- }
- state = dotProp.set(state, `todos.${index}.complete`, true)
- var collection = [1, 2, {a: [12, 17, 15]}];
- var newCollection = update(collection, {2: {a: {$splice: [[1, 1, 13, 14]]}}});