Search code examples
javascriptreactjsreduxfile-upload

How could I handle a file upload with react and redux?


I encounter some issues when I try to implement a file uploader in my react-redux application. Until now, I have handled all the other inputs in this way :

All the inputs have a name and a value. When they are changed, they call the same function.

This function dispatch an action, so in the container of the component, there is :

onInputChange: (name, value) => {
  dispatch(inputValueChange(name, value));
}

This is the action creator :

export const inputValueChange = (name, value) => ({
  type: INPUT_VALUE_CHANGE,
  name,
  value,
});

And now in the reducer, there is a case corresponding to this action :

case INPUT_VALUE_CHANGE:
  return {
    ...state,
    [action.name]: action.value,
  };

This works for all my inputs of type text and the selects elements. If i send with the same action the name "image" (which corresponds to the name of the element in the state) and as a value e.target.files[0], I can see the expected informations with a console.log in the reducer.

See the image

But the state isn't updated and I don't understand why. I suspect this could be because I try to update an element of the state which is actually an object. But this method worked for the elements of the state which are arrays. I tried to give to the state an initial value of null. In this case the state is updated and image is an empty object.

So how could I update my state correctly ?

After this, I will use all these elements to post data to my API. I planned to do the following stuffs just before the call to the API :

const bodyFormData = new FormData();
bodyFormData.append('image', image);  //image is the object which I put in the state
// Then i will do a post request on /api/upload by giving it bodyFormData

Does this sound OK ?


Solution

  • I solved my problem. It was quite tricky.

    The solution was to do a console.log(image) when I give it back to the component. This would have enabled me to see that the informations of the image were given to the component from the redux state. Actually, the state was rightly updated but Redux Dev Tools cannot read this kind of objects, so it shows an empty object whereas the object wasn't empty.

    Good to know !