Reputation: 53
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
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
Reputation: 6742
your action.productId
is an object
not a string
const toggledProduct = newProducts.findIndex( (el) => el.id === action.productId.id /** <--here */ );
Upvotes: 1