I'm about 3 weeks into my #100DaysOfCode challenge, and the last two 'days', I've been wrestling with React, async and promises, as well as useEffect and its shenanigans. Today I made some progress which was nice, but I wanted to quickly document the things I've done/learned in a short blog post for Future Adam™ because he's a bit of an idiot sometimes and will likely forget this.

Fetching for an initial render from within the useEffect hook, can be done like so:

  useEffect(() => {
    const fetchData = async() => {
      const data = await getAllPosts();
      setPosts(data);
    }
    fetchData();
  }, []);

Note a few things:

  1. We need to wrap an async function within useEffect, as it doesn't support the async keyword on the call to useEffect. If you try, it'll start complaining about Promise<void> resolutions because it doesn't know what you're trying to do.
  2. We can then call the inline function within useEffect directly, and this gives us the output we want. I don't know why useEffect doesn't support async as part of the call, but here we are. I really don't like having to do this, I'd prefer to use a separate hook called useEffectAsync or something, that'd be nice. I'm sure there's a valid reason™ why it wont let us do it OOTB though.
  3. Note the empty array of dependencies being passed into useEffect. This tells React 'only run this on first post-render please'. If you find yourself passing dependencies of anything other than basic props, you may be in for a bad time with infinite re-renders due to how React can treat underlying dependencies with what it considers a 'change' (and thus a re-render). This is the part I'm still a bit fuzzy on tbh. I may dig into this a little deeper in a separate post.

If you want to do something with some basic props:

  useEffect(() => {
    const fetchData = async() => {
      const data = await getPost(props.titleKey);
      setPost(data);
    }
    fetchData();
  }, [props.titleKey]);

I still get a bit tricked up with async code in Javascript/Typescript. If you're like me and need to do some further reading, here are some good resources I've found that have got me to this point (and which I still need to spend some time staring at):

React Hooks & Fetching Data: https://www.robinwieruch.de/react-hooks-fetch-data

Async/Await in TypeScript: https://blog.logrocket.com/async-await-in-typescript/