Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

clean up async requests in react useEffect hook using abort controller

useEffect(() => {
    const controller = new AbortController();
    const { signal } = controller;
    async function fetchData() {
      try {
        let response = await fetch(`https://example.com/${x}`, { signal });
        if (response.ok) {
          let data = await response.json();
          console.log(data);
        }
      } catch (error) {
        console.log(error);
      }
    }
    fetchData();

    return () => {
      controller.abort();
    };
  }, []);
 
PREVIOUS NEXT
Tagged: #clean #async #requests #react #useEffect #hook #abort #controller
ADD COMMENT
Topic
Name
4+8 =