How to add objects into array on specific position with setWayPoints() instead of wayPoints.splice? (useRecoilState)

Viewed 71

I currently have a recoil global State Array with Objects (Default: Start and Destination) and i want to add Waypoints in between of them. On pressing a green plus button, new Waypoints appear between Start and Destination:

enter image description here

My problem is, that it doesnt appear instantly on clicking on the "add" button, but only if i trigger any other useState. Probably because i am not adding the waypoints into the array with: "setWayPoints()" but with "wayPoints.splice". Is there any way to add them into the array with "setWayPoints()"?

The code for adding Waypoints into the global State Array:

<MaterialCommunityIcons
      selectable={selectable}
      style={styles.addIcon}
      name="plus-circle"
      size={30}
      color={"green"}
      onPress={() => {
        wayPoints.splice(key + 1, 0, {
            coordinates: { longitude: 0, latitude: 0 },
            place: "",
            placeholder:
              key === wayPoints.length - 1
                ? "Destination"
                : "Waypoint",
       })
      console.log(wayPoints);
    }}
 /> 

If you need any further information, feel free to ask!

Thanks in advance!

3 Answers

Try this?

wayPoints.splice…
setWaypoints(wayPoints)

I fixed the problem by replacing:

onPress={() => {
        wayPoints.splice(key + 1, 0, {
            coordinates: { longitude: 0, latitude: 0 },
            place: "",
            placeholder:
              key === wayPoints.length - 1
                ? "Destination"
                : "Waypoint",
       })

with:

onPress={() => {
        let old = [...wayPoints];
        old.splice(key + 1, 0, {
           coordinates: { longitude: 0, latitude: 0 },
           place: "",
           placeholder:
           key === wayPoints.length - 1
             ? "Destination"
             : "Waypoint",
        });
        setWayPoints(old);
       }}

Here's a simple code that allows you add and items to array before or after current item's index

export const arrayAddItem = ({array, itemValue, index, position = 'after'}) => {
    const increasingCoeff = position === 'after' ? 1 : 0;
    return [
        ...array.slice(0, index + increasingCoeff),
        itemValue,
        ...array.slice(index + increasingCoeff)
    ];
};

Example:

const data = [
 {
  name: 'Yoda'
 },
 {
 name: 'Luke'
 },
 {
 name: 'Vader'
 }
]

console.log(arrayAddItem({
  array: data,
  itemValue: {name: 'Lea'},
  index: 1, // an index, after (or before) of which we add a new item to array
  // position is optional and default is 'after', but you can also add an items 'before' the specified index.
}))

The result is supposed to be

[
 {
  name: 'Yoda'
 },
 {
 name: 'Luke'
 },
 {
 name: 'Lea'
 },
 {
 name: 'Vader'
 }
] 

Or if you need to add new value to specific index, use this code:

export const arraySetValueByIndex = ({array, itemValue, index}) => {

    const startPart = array.slice(0, index);
    const endPart = array.slice(index + 1);
    return [
        ...startPart,
        itemValue,
        ...endPart
    ];
};
Related