React native, multiple records getting pushed after 2nd object being pushed onto the array

Viewed 28

React Native, Im trying to check the whether the object is present in the array or not, if present Im replacing the object with the new one, but after the 2nd object is inserted 3rd object is pushed twice, 4th object 4 times, Im not understanding why this behaviour is happening, is it because of immutable array or what?

useEffect(() => {
        if (route.params && route.params.lookup_scan) {
            showShipments();
        }
    }, [route]);

    const showShipments = () => {
        if (SegregationContext.shipments.length > 0) {
            SegregationContext.shipments.forEach((item, key: number) => {
                if (item.lookup_scan === route.params.lookup_scan) {
                    SegregationContext.shipments[key] = route.params;
                } else {
                    SegregationContext.shipments.push({ ...route.params });
                }
            });
        } else {
            SegregationContext.shipments.push(route.params);
        }
        setShipments([...SegregationContext.shipments]);
        setIsLoader(false);
    };
1 Answers

what the solution was:

const index = shipments.findIndex(i => i.lookup_scan === newobj.lookup_scan); // Returns 2.
if (index === -1) {
    shipments.push(newobj);
} else {
    shipments[index] = newobj;
}

This is what I did but it didnt seem to work bcz it added the object once again after finishing the loop:

if (shipments.length > 0) {
    shipments.map((item, key: number) => {
        if (item.lookup_scan === newobj.lookup_scan) {
           shipments[key] = newobj;
        }
    });
    shipments.push(newobj);
} else {
    shipments.push(newobj);
}

This is what I was doing:

if (shipments.length > 0) {
    shipments.map((item, key: number) => {
        if (item.lookup_scan === newobj.lookup_scan) {
           shipments[key] = newobj;
        } else {
            shipments.push(newobj);
        }
    });
} else {
    shipments.push(newobj);
}

actual code:

if (SegregationContext.shipments.length > 0) {
    SegregationContext.shipments.forEach((item, key: number) => {
        if (item.lookup_scan === route.params.lookup_scan) {
            SegregationContext.shipments[key] = route.params;
        }
    });
    SegregationContext.shipments.push({ ...route.params });
} else {
    SegregationContext.shipments.push(route.params);
    }
setShipments([...SegregationContext.shipments]);
Related