Egghead Newbie
Egghead Newbie

Reputation: 53

arr.findIndex() returns -1

I'm afraid it should be obvious since my affair is based on normal Vanille JS. Anyhow, for any reason I cannot get my issue fixed. Anyhone who can help me out?

Snapshot of my code in reducer:

> case TOGGLE_PRODUCT:
>       const newProducts = [...state.allProducts];
>       console.log("All products: ", newProducts);
>       console.log("Passed product: ", action.productId);
>       console.log("Should have found: ", newProducts[1]);
>       const toggledProduct = newProducts.findIndex(
>         (el) => el.id === action.productId
>       );
>       console.log("Found: ", toggledProduct);

Output in console:

All products:  Array [
  Product {
    "amount": 0,
    "department": "Molkereiprodukte",
    "id": "id1",
    "product": "Milch 3,5%",
    "status": false,
  },
  Product {
    "amount": 0,
    "department": "Molkereiprodukte",
    "id": "id2",
    "product": "Yoghurt",
    "status": false,
  },
  Product {
    "amount": 0,
    "department": "Ceralien",
    "id": "id3",
    "product": "Müsli",
    "status": false,
  },
]
Passed product:  Object {
  "id": "id2",
}
Should have found:  Product {
  "amount": 0,
  "department": "Molkereiprodukte",
  "id": "id2",
  "product": "Yoghurt",
  "status": false,
}
Found:  -1

Why does the find() method not return a result???

Thx in Advance!

Upvotes: 1

Views: 60

Answers (2)

JustRaman
JustRaman

Reputation: 1161

findIndex is used to find desire index of the element you need Array.find to get element data. Reason you are getting -1 is because action.productId is an object. You need to compare action.productId.id


const toggledProduct = newProducts.find(el => el.id === action.productId.id );


Upvotes: 1

Hend El-Sahli
Hend El-Sahli

Reputation: 6742

your action.productId is an objectnot a string

  const toggledProduct = newProducts.findIndex(
    (el) => el.id === action.productId.id /** <--here */
  );

Upvotes: 1

Related Questions