0

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.

1 Answer 1

1

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} />
Sign up to request clarification or add additional context in comments.

1 Comment

hmm makes sense now that i am thinking of it. I was not sure how to write it. I will give it a try and let you know. Thank you for your answer

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.