0

I am trying to setup a functional component that allows the user to copy/paste their clipboard image into the app. In useEffect, I setup document.onpaste . This was working and I was able to get the image and upload it. But I need to have it update the state after paste, so that I can allow them to paste multiple images and keep them in array in state.

I've simplified the problem below. Basically when I paste I want to have it update the counter value, but it doesn't. Counter always = 0. If I use normal react button onclick event, it works fine. I'm guessing the onpaste event is outside of React, but then,

How can I process the paste event and also update the functional state?

import React, { useEffect, useState } from 'react';

const AddAttachmentsContainer = ({ zoneid, tableid, field }) => {
  const [counter,setCounter]=useState(0);

  useEffect(() => {
    document.onpaste=(e)=>{GetImage(e);e.preventDefault()}
  },[])

  const GetImage = (e) => {
    setCounter(counter+1)
    console.log(counter)
  }
 }
mike hennessy
  • 1,359
  • 1
  • 16
  • 35

1 Answers1

0

If I am not mistaken, I'll bet that the state is updated. useState will update the state and trigger a re-render. Since it is asynchronous, console.log will be called with the old state value.

useEffect(() => console.log(counter), [counter]);

... don't forget to add counter in the second argument of useEffect. see here...

Also see here

Alternatively, of course, you can also use refs, but be aware of the use cases for them. It is easy to allow refs to unnecessarily spread through your code.

To be honest, it might be wise to just setCounter in the useEffect you already have and call your GetImage function afterwards... from there, you can retrieve counter. There are multiple approaches to this.

spencer741
  • 965
  • 1
  • 10
  • 22