Uploading file to server with React-hooks, Redux and Multer: PART 2
Hello and welcome to the second and final part of this blog. In this part, we will be talking about Redux. Sit back and enjoy your reading.
In the last aspect, we discovered how to create the form uploads with react and how to connect it with redux, even though we are yet to create the redux until now. The brief of this part is this: we will learn how to create data(payload) to send to react from the database, and how to receive data(payload) from the back-end and database.
Enough of the talking, let’s kick on.
We will have two root folders under src
namely actions
and reducers
. I will be telling you what each folder means by name, and what file we will have in them. Let’s start with the action folder.
First why should you use Action creators?
Action creators are more maintainable. Updates to an action can be made in one place and applied everywhere. All instances of an action are guaranteed to have the same shape and the same default values. -source: redux.js.org
Second, what are Action creators?
An action creator is a function that creates and returns an action. -source: dacembersoft.com
Let’s see an example of action creators below:
export const getUserDetailsRequest = id => ({
type: USER_DETAILS_REQUEST,
payload: id,
});
You can learn more from these two sources: Redux.js.org and Dacembersoft.com
Therefore, for our case, let’s see what we have as the action creator
import axios from "axios";export const createBook = (payload) => async (dispatch) => {
try{
const config: {
header: {
"Content-Type": "multipart/form-data"
}
}
const res = await axios.post("api/books", payload, config);
dispatch({
type: "GET_BOOKS",
payload: res.data
});
}
} }
}
All that’s different is the content-type
aspect. We changed it from application/json
to multipart/form-data
.