0

I am newly learning react, and this is my first go at using useEffect and understanding state. I'm calling an api to get info which is working as intended, and using useEffect to set the data I retrieve into a stateful variable. My issues are arising when I attempt to display this data. I'm receiving an error that I have an undefined property of "name". Clearly, I'm doing something amiss and would appreciate any input to lead me in the right direction. I've attched an image from my console showing the info from the api, I'm attempting to display the name and some other info later on. Cheers.

All code is within a function

const [authorKey, setAuthorKey] = useState("OL23919A");

const [authorData, setAuthorData] = useState();

useEffect(() => {
  getAuthors(authorKey).then((data) => {
    console.log(data);
    setAuthorData(data);
    console.log(authorKey);
  });
}, [authorKey]);

within my function's return (this is where my issue lies - error states .name is undefined)

<Typography name ={authorData.name}></Typography>

as well to note, I'm setting the key of each author in the api using an onClick:

onClick={() => setAuthorKey(author.key)}

Am expecting to print out author name in the JSX

Phil
  • 157,677
  • 23
  • 242
  • 245
CheckDeck
  • 5
  • 3
  • The API call is not synchronous, this means that on the first render the data will be undefined. You will need to account for this by either rendering nothing, a loading symbol, a skeleton, etc until the api call has finished. For some just waiting for authorData to not be undefined is enough, for others they keep better track of the state of the request (pending, error state, validating, etc). – Jacob Smit Nov 16 '22 at 23:19
  • FYI the error is saying it cannot read property `name` of `undefined` meaning it is `authorData` that is `undefined`, not `name` – Phil Nov 16 '22 at 23:19

0 Answers0