How to update the value in action creator - react

Viewed 58

i am trying to update my response in the action creator.

Once then i receive response i am updating the time zone(as of now hardcoded)

Here the response

 data = [
 {
   "created": {timestamp: "2018-05-12T16:55:32Z", Id: "234j", name: "jim"}
    "id": "804690986026920900000061579629"
    "lastUpdated": {timestamp: "2018-05-12T16:55:32Z", Id: "234j", name: "jim"}
    "note": "standard 9"
 },                             
 {
   "created": {timestamp: "2018-05-12T17:49:32Z", Id: "444a", name: "antony"}
    "id": "804690986026920900000061579630"
    "lastUpdated": {timestamp: "2020-05-12T16:49:32Z", Id: "444a", name: "antony"}
    "note": "standard 9"
 },
 {
   "created": {timestamp: "2018-05-12T17:55:12Z", Id: "123m", name: "mark"}
    "id": "804690986026920900000061579631"
    "lastUpdated": {timestamp: "2020-05-12T17:49:12Z", Id: "123m", name: "mark"}
    "note": "standard 9"
 }
];

action.js

then((results) => {
  const hardcodedValue =  "2020-05-22T04:49:44Z"
  const getLocaltime = results.data.map((updatetime)=>{
    return {...updatetime, lastUpdated.timestamp:hardcodedValue}
   //getting error at lastUpdated.timestamp
  })
  results.data = getLocaltime;
    dispatch({
      type: "RECEIVED_DATA",
      payload: updateId === '' ? {} : results,
    })
2 Answers

Thats not a valid object:

{ ...updatetime, lastUpdated.timestamp:hardcodedValue }

Try fixing it to:

{ ...updatetime, lastUpdated: { ...updatetime.lastUpdated, timestamp: hardcodedValue } }

You could also do it like this:

updatetime.lastUpdated.timestamp = hardcodedValue;
return {...updatetime}

This would update the lastUpdated object and since you return a new outer object, the reference would change and you would not lose any data.

The easiest way, since its new data and the object reference can stay the same, you can just mutate it like this:

then((results) => {
  const hardcodedValue = "2020-05-22T04:49:44Z";
  results.data.forEach((row) => {
      row.lastUpdated.timestamp = hardcodedValue;
  });
  dispatch({
    type: "RECEIVED_DATA",
    payload: localAccountId === '' ? {} : results,
  })
Related