Home > Blockchain >  How to use axios in a forEach loop
How to use axios in a forEach loop

Time:05-17

Hi I would like to use axios in a forEach loop in react, but it doesn't work, how should I change this code so that genre, will take the values from genres array

    const [Carousels, setCarousels] = useState([]);
    const genres = ["BestRated", "Newest"];
    useEffect(() => {
        const getCarousels = async (genre) => {
            try {
                let res = await axios.get(`http://localhost:4000/api/carousels/` genre);
                setCarousels([...Carousels, res.data]);
                console.log(Carousels);
            } catch (err) {
                console.log(err);
            }
        }
        getCarousels();
    });

CodePudding user response:

this is how I would go about it :

  const [Carousels, setCarousels] = useState([]);
    const genres = ["BestRated", "Newest"];
    useEffect(() => {
        const getCarousels = async (genre) => {
            try {
                const fetchCarouselPromises = geners.map(genere=>await 
                  axios.get(`http://localhost:4000/api/carousels/` genre)
                )
                Promise.all(fetchCarouselPromises).then((values) => {             
              setCarousels([...Carousels,...values.map(value=>value.data)]);
                });
                // btw the new setted value Carousels
                // is not gonna be available until the next render
            } catch (err) {
                console.log(err);
            }
        }
        getCarousels();
    });

CodePudding user response:

You can make use of Promise.all and set the state with extending its previous value.

const [carousels, setCarousels] = useState([]);
const genres = ["BestRated", "Newest"];

useEffect(() => {
    try {
        const fetchCarouselPromises = geners.map(genre =>
            axios.get(`http://localhost:4000/api/carousels/`   genre)
        )
        Promise.all(fetchCarouselPromises).then((values) => {
            setCarousels(prev => [...prev, ...values.map(value => value.data)]);
        });
    } catch (err) {
        console.log(err);
    }
});


CodePudding user response:

you need to use Promise.all

Promise.all(fetchCarouselPromises).then((values) => {             
              setCarousels([...Carousels,...values.map(value=>value.data)]);
                });
  • Related