Skip to content
Advertisement

create image in React from backend dataURL

I’m trying to get a snapshot of HTML canvas like so:

    const canvas = canvasRef.current
    let image = canvas.toDataURL('image/jpeg');
    await axios.post('/api/entries/', { dataURL: image })

which seems to be working, and connected properly to the database.

But I can’t figure out how to use the dataURL to create an image component on the React frontend

I’m able to fetch them from the backend just fine and log the dataURL.

    const pics = await axios.get('/api/entries/')
    pics.data.map((pic) => { console.log(pic.dataURL) })

I guess I’m just not sure of the next steps to get each dataURL into a element

Here is my getPics function:

  const getPics = async () => {
    const pics = await axios.get('/api/entries/')

    return (
      pics.data.map((pic) => (
        <img src={pic.dataURL} key={pic.dataURL} />
      ))
    )
  }

and its used just like:

<div>
  {getPics()}
</div>

Advertisement

Answer

Put the images into a state and put the fetch into a useEffect() function.

const [pic,setPics] = useState();

useEffect(() => {
  const getPics = async () => await axios.get('/api/entries/')
    .then(res => {
    setPics(res.data);
    })
  getPics();
}, [])

Mapping is the correct way to go… when mapping you can throw the data into a img element, this will render every image onto the page. the key value is for react to know the difference between each element.

return (
  {pics.data.map((pic) => (
    <img src={pic.dataURL} key={pic.dataURL} />
  ))}
)
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement