2

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();
    });
5
  • Where exactly is your forEach (as your wrote but it doesn't work)? Commented May 16, 2022 at 14:32
  • I don't have it, I don't know how to implement it. Commented May 16, 2022 at 14:33
  • do you want to sequentially send an http request for each genre? It's hard to interpret the question Commented May 16, 2022 at 14:38
  • Yes, that is what I want to do. Commented May 16, 2022 at 14:40
  • I found out that I have to replace forEach Here is how: stackoverflow.com/questions/37576685/… Commented May 16, 2022 at 14:46

2 Answers 2

1

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();
    });

Sign up to request clarification or add additional context in comments.

Comments

1

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);
    }
});


Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.