0

I tried to fetch names for each of "characters" from https://swapi.dev/api/films/1/ and then show it on page but my page render without nested fetch data. As first Im fetching data from https://swapi.dev/api/films/1/ and then i mapping "characters" value, its array of urls and making axios for each of them, result push to array, when I console.log(array) array after it Im getting "value below was evaluated just now", when I JSON.stringify(array) console show me nothing enter image description here

My code:

const getData = async () => {
    try {
        let array = [];
        axios.get(`https://swapi.dev/api/films/1/`)
        .then(firstData=>{ 
            Promise.all(
                firstData.data["characters"].map(url=>{
                    axios.get(url)
                    .then(character=>{
                        array.push(character.data.name);
                    })
                })
            ).then(result=>{
                console.log("array:",array);
                JSON.stringify(array);
                })
        })
    } catch (err ) {
        // errors
        console.log(err,"connection error")
    }
} 

useEffect(() => {
    getData()
}, []);

1 Answer 1

1

You aren't waiting for all of your promises to resolve before logging the array, the main issue is that you don't return the promise from your map function, you could do:

const getData = async () => {
    try {
        let array = [];
        const firstData = await axios.get(`https://swapi.dev/api/films/1/`)
        await Promise.all(
            firstData.data["characters"].map(url=>{
                return axios.get(url).then(character=>{
                    array.push(character.data.name);
                })
            })
        ).then(result=>{
            console.log("array:",array);
            JSON.stringify(array);
        })
    } catch (err ) {
        // errors
        console.log(err,"connection error")
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

ok, thank you, maybe you can tell problem at my main question? stackoverflow.com/questions/63125026/… There I tried to fetch main data then fetch automatically data from arrays but data from additional requests not showing

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.