0

I have an object in my state like :

enter image description here

I have a property sections, that is an array of objects, I want to add an item in the geometri_linestring array of a specific object in the sections array, to do this, I did this in my reducer :

const setPointSuccess = curry(({ point }, state) => {
  const activeTronconId = point.activeTroncon;
  let circuit = state.addedCircuit;
  let sections = circuit.sections;
  let troncon = sections.filter(section => section.tronconId === activeTronconId)[0];
  let disabledTroncons = sections.filter(section => section.tronconId !== activeTronconId);
  const { latitude, longitude } = point;
  let geoLineString = troncon.geometri_linestring;
  geoLineString.push({ latitude, longitude });

  troncon.geometri_linestring = geoLineString;
  disabledTroncons.push(troncon);
  sections = disabledTroncons;
  circuit.sections = sections;
  let addedCircuit = circuit;

  return {
    ...state,
    addedCircuit,
  };
});

So, I think it is not a good code, it can be better, using ramda expressions, but I can't think of doing this, since I went so deep in that object.

Is there a simpler way to do this ?

Any help would be much appreciated.

1 Answer 1

2

I am not sure whether you are asking about redux reducers, in which case I'd suggest you to avoid methods such as push as they mutate the given input...

Also, Ramda and fp in general promote an immutable approach to data transformations...

__ The following should help you do what you need, of course you'd need to find the section (index) you need to operate on.

const addCoordinates = (section, coords, state) => R.over(
  R.lensPath(['sections', section, 'geometry_linestring']),
  R.append(coords),
  state,
);

// ====

const state = {
  sections: [
    {
      geometry_linestring: [
        { longitude: 10, latitude: 20 },
        { longitude: 50, latitude: -320 },
      ],
    }
  ],
};


console.log(
  addCoordinates(0, { message: 'Hello World' }, state),
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js" integrity="sha512-P+CxnI2T1ohL0L2CCoq/FZmfTms2+pOw5xxeYghPovQAmBDdQb6E7Yk74lB/v84c046R1fM2ecfAhFsPzleAag==" crossorigin="anonymous"></script>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.