11

I am currently using Material Ui dropzone to upload multiple files. just wondering what is the best way to add/update files in the redux store. I am currently doing a dispatch action when "onChange" triggers which return all the files on the dropzone and updating the redux state by storing the whole files array which has files object.

please let me know if there is a best way, to handle this.

dev0864
  • 465
  • 2
  • 7
  • 17
  • Your question is very open, What do you need do with the files, do you need process or it is only for send to the server directly ? what are your react and redux version? – Victor Carrera May 10 '20 at 02:22
  • 1
    I need to send the files to the server post endpoint directly. I am using react 16.13.1 and redux: 4.0.5 – dev0864 May 10 '20 at 04:09
  • In this case is much better don't use the redux store for that. You can call to API post directly in the component. There are other similar to dropzone library that maibe you can take a look https://github.com/pqina/filepond, this include the post directly . Store is more recommended for share serializables between components. – Victor Carrera May 10 '20 at 23:17

2 Answers2

10

One of the key rules of Redux is that non-serializable values should not go into the store. Because of that, file objects should not be kept in the Redux store if at all possible.

Dekel
  • 60,707
  • 10
  • 101
  • 129
markerikson
  • 63,178
  • 10
  • 141
  • 157
  • Then just store in local state and send it to actions and make an post API call? I guess this is the only way without adding it to the redux store. Does it sounds good? – dev0864 May 10 '20 at 01:54
  • Largely, yes. Unless there are many other components that really need access to those files anyway, there's not really a good reason to have them in the Redux store in the fist place. – markerikson May 10 '20 at 01:58
  • One more question, where would be an idle way of making API call to send files to server without a submit button. The method "onChange" gives all the files in the dropzone and method "onDrop" only gives us only files being dropped at that moment. I am thinking of making a API call on "onDrop" please let me know. – dev0864 May 10 '20 at 14:30
5

I had a similar problem and ended up using this:

URL.createObjectURL(file)

It returns a url like blob:http://example.com/f331074d-a7f3-4972-9c37-96b490a4dd96 which is just a string and can be used in img tag's src attribute. Not sure what Material Ui dropzone returns, but this works with File objects returned by <input type="file" />

jetpackpony
  • 1,270
  • 1
  • 12
  • 22