Search code examples
javascriptnode.jsimmutability

Immutability-helper - How to update this value?


I have a JSON object stored in "aggRequest", this is my JSON

{
    "state":{
       "controllerStates":[
       ],
       "rulesetStates":[
          {
             "rulesetContext":{
                "dialog_stack":[
                   {
                      "dialog_node":"root"
                   }
                ],
                "dialog_turn_counter":1,
                "dialog_request_counter":1,
                "_node_output_map":{
                   "node_1_1504607088493":[
                      0
                   ]
                },
                "branch_exited":true,
                "branch_exited_reason":"completed"
             },
             "convId":"XXXX",
             "modelRef":"XXXX"
          }
       ],
       "selfCallCount":0,
       "sysTurnCount":2,
       "userTurnCount":2
    },
    "context":{
       "conversationContext":{
          "brand":"XXXX",
          "channel":"XXX"
       },
       "userData":{
          "tokens":[
          ]
       }
    },
    "XXXXX":"2.0",
    "XXXXX":"XXXXX",
    "XXXXX":"XXXXX",
    "XXXXX":"XXXXX",
    "XXXXX":"XXXXX",
    "turnStart":"2018-08-10T15:21:36.075Z",
    "turnEnd":"2018-08-10T15:21:36.076Z"
 }

I am trying to set the turnEnd to a new date using moment, the date is being created correctly, and I believe my function is correct:

    const update = require('immutability-helper');

    function updatePropertyValue() {
    const momentDateChange = getRunDateAsString();
    update(aggRequest, {
          $set:
            {
            turnEnd: `${momentDateChange}`,
            },
      });
     console.log(aggRequest)
}

When I view the addRequest console.log, the date has not been updated. Why would that be?


Solution

  • The whole idea of immutability is that you can not change the data. Instead you creating a new one. Like in the example below:

    const update = require('immutability-helper');
    
    const data = {
      "turnEnd":"2018-08-10T15:21:36.076Z"
    };
    
    const newData = update(data, { $set: { turnEnd: 'voala!' } });
    
    console.log(data); // it is immutable, right?
    console.log(newData); // it is new version of the data
    

    In order to solve the issue change your code to use updated (new version) of your data:

    const updateAggRequest = update(aggRequest, { $set: { turnEnd: momentDateChange } });