Handling asynchronous requests in react using redux-saga, building full CRUD app
Hi,
We have talked about redux in previous article, check it out, where I have tried to explain the best way to write, understand redux.
if you don’t know redux, it’s state management for react, where it comes more handy to share your state among any component inside your application instead of passing it from parent to children and then ends up with this:
What Are you going to do
We are going to build application where redux is been used with redux-saga to handle our fetch requests, we will build crud-users app
CRUD: Create, Read, Update, Delete
I will go through every package that we are going to use with its purpose difenition:
- redux: Our main state management.
- react-redux: To inject state in the components.
- redux-saga: To handle fetch-requests by using generator functions.
- reduxsauce: To define our types and actions, easily manage our types.
- json-server: Get a full fake REST API with zero coding in less than 30 seconds (seriously😎).
- seamless-immutable: To make your state immutable.
for an API we will use: jsonplaceholder
Install
to start we will use create-react-app to install, but ….?
we will eject it directly which is something you might do depending on your project. I’m doing it because I like that 😃
I will call my project crud-users, feel free with naming:
I’m using Yarn, but you can use npm as well if you prefer that too:
yarn add -g create-react-app
create-react-app crud-users
cd crud-users && yarn eject
now it’s ready to go
remove everything in the src folder without index.js
serviceWorker.js
.
if you're interested to build Progressive web apps, you might enable serviceWorker in index.js
by calling register function of unregister
// default : serviceWorker.unregister()
// change to: serviceWorker.register()
1. Setup API
We will use json-server because it offers simplicity, no need to configuration and also you can set your response from real api to it which what we are going to do it.
Installing first json-server globally:
yarn add -g json-server
Make file in your project directory called: db.json => you’re free with naming. now we will fetch users by api :
https://jsonplaceholder.typicode.com/users/
This is will return json response with 10 users copy them to your db.json.
In package.json: set this command to run json-server under scripts.
"watch-db": "json-server --watch db.json --port 4000"
now run it:
yarn watch-db
and you will get link: http://localhost:4000/users, with 10 users
leave this running and let’s go to the next step.
2. Routing
For routing we will use react-router-dom, to handle our navigation route between pages.
✍️. you might use react-router-redux which is better way to handle our routing actions.
we will set three pages:
A. Home: /,
B. Users : /users
C. Add user: /add-user
create a file under Containers/routes.jsx:
create a file in the same directory called Routing.jsx
3. Redux
yarn add redux react-redux redux-logger seamless-immutable reduxsauce
Install these packages.
Then make file in this path : src/redux/UserRedux.js
In this file we will define our Types and Actions that used by redux
And than create a file where you can create your store:
src/redux/index.js
4.Setup CRUD API
We have `json-server` running, now what we want to do is setting our API to receive functions where we could get Users, Updating them, delete them, and also add new user to them.
Create a file under this source: src/utils/apiConfig.js
now with this, we will move to setup out Saga 🙂.
5.Saga
Install :
yarn add redux-saga
✍️. explanation above line of code
Before we start, you need to know that saga works with generator functions .
✍️. If you’re not familiar with generator functions, it is not so difficult! you need to understand that with generator function, you add * with function definitions and inside this function you must use
yield
keyword, like return async call, …
Create folder under src directory with name saga (feel free with naming).
We will create a file with name UserSaga.js
inside this folder :
Now If we are going to use more than userSaga, than you might better to set them all together and run them, checkout this in src/saga/index.js
this will export all our sagas together, we can run them as root.
so make file with src/saga/index.js
and write in it this:
now in src/redux/index.js
we need run our sagas:
checkout new code with // added comments
6.Connect
Now we are ready for fetching users, and use them inside our components.
Connecting with our components will be by using package react-redux
yarn add react-redux
now update src/index.js
with this:
If you navigate to Routing.jsx
there we will fetch users by using redux-saga
if you have already knowledge about redux, this is a typically redux injecting props.where you have connect
from react-redux as higher order component will takes two parameters one is the state, and other is dispatch.
Can you do this
connect(mapStateToProps)(AnyComponent)
: Sure you can if you know that you don’t need to dispatch events in this component, you could use than just the state, But you cannot pass dispatchProps as a first parameter, you need to provide first parameter and in that case just empty object:
connect({}, mapDispatchToProps)(AnyComponent)
Run:
run: yarn start
or npm run start
in the browser, open devtools, you should see this:
Styling: it is up to you, I’m not really concentrating in styling in this tutorial, the main concept is using redux-saga, and that’s why I didn’t use it a main point. But in the end my app will be like this:
This is for fetching users and the same will be for delete, add, update Users.
For that checkout my repo for rest of code.
=======================================
We have built a full CRUD app with redux-saga.
I have updated my code with all features, what I would recommend that you try it first by own and than check it with my code in Github.
This article has been shared also on Coderreview.io check it out for more articles.
If you have questions feel free to contact me on:
what’s next: “PWA”, “react with typescript the important parts” and more…