Serenity Serenity - 3 months ago 15
Javascript Question

return whole object with updated arrays in reactjs

I am having problem in showing the features object with updated features array inside it. For untouched/undeleted part, its working fine but the feature which I delete returns only the features
array instead of showing whole object with features array inside it. What I mean is, if I have an object like this

0: Object
feature_description: "Room Amenities"
feature_type: "roomamenities"
features:Array(6)
_id:"59395255455a5b043c764a29"

1:Object
feature_name: "Room Amenities"
feature_type: "bathroom"
features:Array(3)
_id:"59395255455a5b043c764a29"


Now that When I delete the feature of roomamenities feature type, I get the following result

0:Object
features: Array(5) # 5 not 6 because one item is deleted

1:Object
feature_name: "Room Amenities"
feature_type: "bathroom"
features:Array(3)
_id:"59395255455a5b043c764a29"


instead it should return the following object

0: Object
feature_description: "Room Amenities"
feature_type: "roomamenities"
features:Array(5)
_id:"59395255455a5b043c764a29"

1:Object
feature_name: "Room Amenities"
feature_type: "bathroom"
features:Array(3)
_id:"59395255455a5b043c764a29"


How can I resolve my issue?

Here is my code of reducer

case UPDATE_REQUESTED_FEATURES_SUCCESS:
return state
.update("features", features =>
state.get('features').map(feature => {
console.log("feature", feature);
if (feature.get("feature_type") === "roomamenities") {
return {
...feature,
features: feature.get("features").map(subFeature => {
return subFeature.get("_id") !== action.response.data._id;
})
};
} else {
return feature;
}
})
);


This is the result of features object yielded from reducers by consoling state.get('features')

enter image description here

Answer Source

Your feature objects are ImmutableJS Maps. So replace this:

  return {
    ...feature,
    features: feature.get("features").map(subFeature => {
      return subFeature.get("_id") !== action.response.data._id;
    })
  };

with:

  return feature.set("features", 
      feature.get("features").filter(subFeature => {
          return subFeature.get("_id") !== action.response.data._id;
      })
  );