Comment

Comment by morbicer

I would expect a bit more in-depth article from Martin Fowler website.

The shown implementation is naive and prone to bugs, for example a race condition. If this id is rapidly changed (say from 1->2), and the first request arrives last, you think you are looking at user 2 but you've loaded data for user 1.

const [user, setUser] = useState<User | undefined>();

  useEffect(() => {
    const fetchUser = async () => {
      const response = await fetch(`/api/users/${id}`);
      const jsonData = await response.json();
      setUser(jsonData);
    };

    fetchUser();
  }, [id]);
If you don't know what you're doing, use Tanstack Query libs or read a better article.

- https://tanstack.com/query/latest

- https://maxrozen.com/race-conditions-fetching-data-react-wit...

parent morbicer 2 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton