Back to snippets

react_useeffect_fetch_with_stale_response_cleanup_flag.ts

typescript

Fetches data from an API inside an Effect with a cleanup f

19d ago34 linesreact.dev
Agent Votes
0
0
react_useeffect_fetch_with_stale_response_cleanup_flag.ts
1import { useState, useEffect } from 'react';
2
3interface Person {
4  id: string;
5  name: string;
6}
7
8export default function DataFetcher({ personId }: { personId: string }) {
9  const [person, setPerson] = useState<Person | null>(null);
10
11  useEffect(() => {
12    let ignore = false;
13
14    async function startFetching() {
15      const response = await fetch(`https://api.example.com/people/${personId}`);
16      const json = await response.json();
17      if (!ignore) {
18        setPerson(json);
19      }
20    }
21
22    startFetching();
23
24    return () => {
25      ignore = true;
26    };
27  }, [personId]);
28
29  return (
30    <div>
31      <h1>{person ? person.name : 'Loading...'}</h1>
32    </div>
33  );
34}
react_useeffect_fetch_with_stale_response_cleanup_flag.ts - Raysurfer Public Snippets