Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch data from multiple urls at once?

I have a function that fetches from a url in React

const DataContextProvider = (props) => {
  const [isLoading, setLoading] = useState(false);
  const [cocktails, setCocktails] = useState([]);

  useEffect(() => {
    const fetchCocktailList = async () => {
      const baseUrl = 'https://www.thecocktaildb.com/api/json/v1/1/';
      setLoading(true);
      try {
        const res = await fetch(`${baseUrl}search.php?s=margarita`);
        const data = await res.json();
        console.log(data);
        setCocktails(data.drinks);
        setLoading(false);
      } catch (err) {
        console.log('Error fetching data');

        setLoading(false);
      }
    };

    fetchCocktailList();
  }, []);


How I'm mapping data so far.

const DrinkList = () => {
  const { cocktails } = useContext(DataContext);
  return (
    <div className='drink-list-wrapper'>
      {cocktails.length > 0 &&
        cocktails.map((drink) => {
          return <DrinkItem drink={drink} key={drink.idDrink} />;
        })}
    </div>
  );
};

However I want to fetch from this url also ${baseUrl}search.php?s=martini

I would like a good clean way to do this and set my state to both of the returned data.

like image 934
DGB Avatar asked Nov 25 '25 05:11

DGB


1 Answers

First base the data fetch function on a parameter:

const fetchCocktail = async (name) => {
  const baseUrl = 'https://www.thecocktaildb.com/api/json/v1/1/';
  try {
    const res = await fetch(`${baseUrl}search.php?s=` + name);
    const data = await res.json();
    return data.drinks;
  } catch (err) {
    console.log('Error fetching data');
  }
}

Then use Promise.all to await all results:

setLoading(true);
var promises = [
  fetchCocktail(`margarita`),
  fetchCocktail(`martini`)
];
var results = await Promise.all(promises);
setLoading(false);
DrinkList(results);

Where results will be an array with the responses that you can use on the DrinkList function.

like image 198
ariel Avatar answered Nov 27 '25 18:11

ariel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!