Hooks 11 exercises
Problem

Typing useState with undefined

In this exercise, we have a similar situation to the one we just saw.

We have a function called fetchData where we're fetching data that has id: 1 and name: John.


const fetchData = () => {
return Promise.resolve({ id: 1, name: "John" });
};

Inside this Component, we us

Loading exercise

Transcript

0:00 In this exercise, we have a sort of similar situation to the previous exercise but a little bit different. We have a function called fetchData, where we're fetching some data that has id 1 and name John, which, coincidentally, is the same as this Data interface just here.

0:14 What we want to do is, inside this component, in a useEffect, which is not the best way to be doing data fetching...For this example, it will do. What we do inside this useEffect when the component mounts, we do fetchData. Then we set the data that gets returned into our useState.

0:31 Except we've got a sort of similar problem to last time, which is data doesn't know what it's supposed to be. In this case, instead of a never array, it's being inferred as undefined. Hmm.

0:42 Your job here is to try to figure out how to make that into Data or undefined, because we can't pass in an initial value here to let TypeScript infer. What's happening is we're just getting undefined being inferred in this slot. Your job is to work out how to make this work and the best way to do it. Good luck.