Using uppy .on callbacks in a functional component

When using uppy .on callbacks in an functional component the previous state seems to be overwritten.

See example at https://codesandbox.io/s/optimistic-mclaren-zbyvh?file=/src/App.js

The example displays a simple ui with a drag and drop uploader. When you select a file it should be added to the existing file in the files list, however the newly selected file seems to always wipe out and replace the list.

Is there a way to use the .on callbacks with uppy in a way that does not overwrite the current state?

Hello! This is a common issue with state not syncing. The problem lies within the addFile method. Here’s a simple fix

  const addFile = useCallback(
    file => {
      setFiles(files => [...files, file.name]);
    },
    [setFiles]
  );

The actual error is because the files dependency is stale when the callback is called. The setter method for state can either take a function (as shown here), or it can just take data (as you were doing) as an argument. When we pass it a function, we can take the current value as an a parameter. This means that our state will never be stale.

I hope this helped. Let me know if you have anymore questions
- Andrew