Adding key value pairs to redux store

I am trying to use redux to add key value pairs to my store. However, Im not sure how to accomplish this. In short, i am retrieving data from firebase, I want to add that data to my redux store, but I have to do it one item at a time. My desired structure of my state object is something like this:

reminders
 - reminder key 1
   - reminder title
   - reminder date 1
 - reminder key 2
   - reminder title
   - reminder date 1

and so on.

But I cant figure out how to add children to my state.reminders object

Here is my action:

const fetchReminders = (uid) => async dispatch => {
    firebaseReminders.child(uid).orderByChild("date").on("value", snapshot => {

      snapshot.forEach(function(child) {
        console.log(child.val())
        dispatch({
          type: 'fetchReminders',
          value: child.val(),
          key: child.key
        });
      })

    });
};

so this would dispatch the action for every single item that I retrieve from the database, and then in my reducer I want to add that item to the state tree using action.key as the key. Currently I have

const remindersReducer = (state = initialState, action) => {

    switch(action.type) {

        case "fetchReminders":
             return Object.assign({}, state, {
                reminders: action.value
             });


        default: return state;
    }

};

which is not correct. How can I add a child node to my state.reminders object with the key of action.key, and the value of action.value

1 answer

  • answered 2018-10-17 04:13 uautkarsh

    let initialState = {
      reminders: {}
    }
    
    const remindersReducer = (state = initialState, action) => {
      switch(action.type) {
        case "fetchReminders":
          return Object.assign({}, state, {
            reminders: {
              ...state.reminders,
              [action.key]: action.value
            }
          });
        default: return state;
      }
    };
    
    let state1 = remindersReducer(initialState, {
        type: 'fetchReminders',
        key: 'reminderKey1',
        value: 'reminderValue1'
    });
    console.log(state1)
    
    let state2 = remindersReducer(state1, {
        type: 'fetchReminders',
        key: 'reminderKey2',
        value: 'reminderValue2'
    });
    console.log(state2)
    
    let state3 = remindersReducer(state2, {
        type: 'fetchReminders',
        key: 'reminderKey3',
        value: 'reminderValue3'
    });
    console.log(state3)

    The snippet should help you achieve what you want to do. You can assign an object as the key of action.key by using the following format:

    {
      [action.key]: action.value
    }
    

    Its called Computed Property Names.

    Starting with ECMAScript 2015, the object initializer syntax also supports computed property names. That allows you to put an expression in brackets [], that will be computed and used as the property name. Source