0

I am trying to get data through nested react-router but getting the value undefined.

My data:

const data = [
    {
        id: 0,
        name: "Skateboard1",
        price: 20.10,
        img: picture1
    },
    {
        id: 1,
        name: "Skateboard2",
        price: 80.50,
        img: picture2
    }
]

App.js:

const App = () => {
  return (
    <Router>
      <Switch>
 
        <Route exact path="/shop/:id" render={(itemProp) => <ShopItem shopItemId={itemProp.match.params.id} />} />

      </Switch> 
    </Router>
    
  );
}

ShopItem Component:

const ShopItem = (shopItemId) => {

        const item = data.find((i) => i.id === shopItemId) 
    
    return(
        <div>
               <h2>{item.name}</h2>
        </div>
    )
}

Error:

TypeError: Cannot read property 'name' of undefined

on console.log(shopItemId)

{
  shopItemId: "1"
}

It seems like a silly mistake. But can't get what's wrong.

Please any help would be appreciated

1 Answer 1

1

The function data.find((i) => i.id === shopItemId) didn't find any element that matches the comparison, so item is undefined. shopItemId is an object, so the real value is shopItemId.shopItemId and use == operator since one value is an integer and the other is a string like:

const item = data.find((i) => i.id == shopItemId.shopItemId)
Sign up to request clarification or add additional context in comments.

9 Comments

Yes, I know it's returning undefined, not sure why. Above I have posted the content of the data as well.
Is there anything else would you like to see besides the content of the data?
data looks good, maybe shopItemId has a different value, or it's a string and it's expecting an int.
I have updated my question to show the value of shopItemId. Could you look it again, please?
right, the problem is that shopItemId is a string and the id of the data element is an integer, === operation first checks the types of the values, so 1 is not equal to "1". u can use == instead of === like data.find((i) => i.id == shopItemId)
|

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.