Why u do dis
Why u do dis

Reputation: 458

Typescript React cant find property inside object

Sorry for the confusing title but I didnt know how to title it better.

I am fetching some data from a food api and storing it into a state.

  const [data, setData] = useState<null | {}>(null);

The above stateful variable is initialized as null and then later changes to being an object when the fetching is finished setData(apiData) that has one property called meals which is an array of objects

I am trying to pass the fetched data to a component called Card but i get this error: " Property 'meals' does not exsist on type '{}' "

  data !== null && <Card data={data?.meals} />

I thought that It probably cant recognize the property 'meals' on the object because the data is not done fetching when it tries to access it so i decide to check if the data is not equal to null but that is not working either...

Any idea towards what I am doing wrong ? I am new to Typescript. Thank you in advance.

Upvotes: 0

Views: 217

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 84912

The type {} means "an object with no properties". Thus, you're saying that it will not have a meals property, nor any other. You need to provide a type that matches what the data will look like. I don't know exactly what that type will look like, so you will need to fill in what it's properties are, but an example with some properties i made up is:

interface Meal {
  mealId: string;
  calories: number;
}

interface Data {
  id: string;
  meals: Meal[];
}

// ... used like:
const [data, setData] = useState<null | Data>(null);

// ... and:
data !== null && <Card data={data.meals} />

Upvotes: 1

Related Questions