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

Time:04-15

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.

CodePudding user response:

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]);
  • Related