Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I use the result of a useEffect fetch in a subsequent fetch?

I can’t figure out how to pass a field’s data from one useEffect fetch query (using GROQ) to a second useEffect fetch query using a REST API with URL parameters.

  const [airline, setAirline] = useState(null);
  const [airport, setAirport] = useState(null);
  const { slug } = useParams();

  const url = "https://aviation-edge.com/v2/public/airportDatabase?key={myKeyHere}&codeIataAirport=";

  useEffect(() => {
    sanityClient
      .fetch(
        `*[slug.current == $slug]{
          ...
          hubIataCode,
          ...
        }`,
        { slug }
      )
      .then((data) => setAirline(data[0]))
      .catch(console.error);
  }, [slug]);

  useEffect(() => {
    fetch(`${url}${airline.hubIataCode}`)
      .then((response) => response.json())
      .then((data) => setAirport(data));
  }, []);

Perhaps the two need combining?

To my surprise there isn’t much information on using data from the first API call on the second with useEffect, or perhaps I can’t word my search correctly.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Option 1 – Add airline as dependency to the 2nd useEffect and bail out if it’s null:

useEffect(() => {
  if(!airline) return;

  fetch(`${url}${airline.hubIataCode}`)
    .then((response) => response.json())
    .then((data) => setAirport(data));
}, [airline]);

Option 2 – combine requests to a single useEffect using async/await:

useEffect(() => {
  const fetchData = async () => {
    try {
      const [airline] = await sanityClient.fetch(`*[slug.current == $slug]{...hubIataCode,...}`, { slug });
      const airport = await fetch(`${url}${airline.hubIataCode}`).then((response) => response.json());
      setAirline(airline);
      setAirport(airport);
    } catch (e) {
      console.error(e);
    }
  };
  
  fetchData();
}, [slug]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading