1

I have an array of trying to grab four thumbnail jpgs' from using the vimeo API. I have an array of video ids

const vimeo = [
    "325845565","325846054","325848270","325849439"
]

I'm using setState to import and use the arrays

import vimeo;

const [data , setData ] = useState(vimeo)

I have a separate state where I would like to store the thumbnails data:

const [thumbNails, setThumbNails] = useState({
    data : []
})

Id like to be able to iterate over each vimeo id inside the useEffect hook. I'm using axios something like:

useEffect(() => {
    const fetchData = async () => {
        data.map(videoID => {
            const result = await axios(`http://vimeo.com/api/v2/video/${data[0]}.json`);
            setThumbNails({
                data : result
            })
        }
        })

    fetchData()
},[])

but with this code im getting the following error:

Parsing error: Can not use keyword 'await' outside an async function

Any thoughts? Thanks.

James
  • 1,355
  • 3
  • 14
  • 38
  • 1
    Parser error aside (you've just misplaced the `async` declaration, it should be on the `data.map` callback not `fetchData`) how do you expect this code to work? At the moment it would always overwrite the last thumbnail that you fetch. Also, `result` in this case would be an axios response, I presume you'd want `data: result.data`... – James May 22 '19 at 14:38

1 Answers1

0

That a look at this answer and also what I found on google

You will need to use Promise.all and then setState with the array returned

const fetchData = async () => {
    let fetchedResult = await Promise.all(data.map(videoID => 
        axios(`http://vimeo.com/api/v2/video/${data[0]}.json`)
    ))
    fetchedResult.map(data => setThumbNails({
            data : result
        }))
}
Vencovsky
  • 28,550
  • 17
  • 109
  • 176