React Redux walk through.

Create,Delete, Update,Read with redux, axios and redux-thunk

Mercy Jemosop
6 min readJul 19, 2021

Introduction to redux basics

Redux is a pattern and library for managing and updating application state, using events called “actions”. It serves as a centralized store for state that needs to be used across your entire application, with rules ensuring that the state can only be updated in a predictable fashion. When to use redux:

-You have large amounts of application state that are needed in many places in the app

-The app state is updated frequently over time

-The logic to update that state may be complex

-The app has a medium or large-sized code base, and might be worked on by many people

Redux Terms

State Management, a state is the source of truth that drives an app(pageNumber). This value is managed by store.

const [pageNumber, setPageNumber] = useState(0);

View, this is the description of the UI based on the current state.

Action

These are events that occur in the app based on user input, and trigger updates in the state. The action contains payloads and type. Actions are the only way to get into the store.

Type field should be a string describing the action.

Payloads field , is what is keyed in your actions and passed around between reducers in your redux application.

action object

Action Creators

This is a function that creates and returns an action object.

Reducer

This is a function that receives the current state of an action object, decides how to update the state if necessary and returns a new state. Reducer rules

Reducer

Store

This is a state container which holds the application’s state. There can be only one application store in an application. The store is created by passing in a reducer. It also has a method that returns the current state value.

console.log(store.getState())

Dispatch()

This is the method used to dispatch actions and trigger state changes to the store. React-redux is simply trying to give you convenient access to it. Dispatch is not available on props, you can use connect.

store.dispatch({ type: 'GET_USER' })

Let’s Get started.

To get started with redux we need to install a couple of packages. We will use redux-thunk middle-ware package which allows us to write action creators that return a function instead of an action. The thunk can be used to delay the dispatch of an action or to dispatch only if a certain condition is met.

axios is a library used to make request to an API return data and manipulate the data

npm install redux react-redux
npm install --save redux-thunk
npm install axios

POST REQUEST TO AN API

assuming you already have your API and UI design ready. We will add a user to using our API Endpoint.

Step 1:

Create an action class example. action.js add the action below. (user payload will hold our data).

Optional: you can create an action type class to hold your constant types. Example action_type.js. You will then import it to your action class

export const ActionTypes ={
UPDATE_USER: 'UPDATE_USER',
GET_USER: ' GET_USER',
GET_USERS: 'GET_USERS',
ADD_USER: ' ADD_USER',
};
add user action
/// if you create an action type class
type: ActionTypes.ADD_USER,

Step 2:

Create action creator function which makes an API POST request. It then dispatches the add action. Action creator can be in the same class as the action or you can create a class to hold functions for action creators. Create action_creators.js class to hold all your creator function.

Step 3:

Create a reducer class to update the state based on the actions passed. Create a class e.g reducer.js. The reducers can also be in an if -else statement.

Reducer

step 3 (b).

Create a class to combine your reducers, if you are planning on adding more reducers, this enables them to manage their own slices of state.

4. Store

Create a store for our app (store.js),import redux-thunk our middle-ware. an app can only have one store.

Store.js

5. Add the store to our application

In your index.js, import the store and provider, then enclose the app with a provider.

Step 6: Update the UI/View

Put Request

PUT request is similar to Post request, it is used to send data to the API to update or create a resource. The difference between the two is that calling PUT request multiple times produces the same results but POST request creates same resource/product multiple times.

Step 1:

Create Update action. Add this action to actions.js class you created

export const updateUser = () => {
return {
type: 'UPDATE_USER'
}
}

Step 2:

Create action creator function which makes an API PUT request. Update the action_creator.js class which holds your addUser creator function with update user.

/// update the existing data of a user
export const updateUserAction = (user, id) => {
return (dispatch) => {
axios.put(`https://your url/${id}`, user)
.then(response => {
console.log(response);
dispatch(updateUser());
dispatch(getUsersAction());
})
.catch(error => {
console.log(error);
});
}
}

Step 3:

Update your reducer in-order to update our state based on the action we pass(update action).

case ActionTypes.UPDATE_USER:
return { ...state, id: action.payload }

Step 4:

Update the user Update screen to be able to update user data.

Yeeey!!! we done with updating user details. In-case your code is not working here is a GITHUB link for the project.

GET Request

The GET method is used to retrieve data from a server at the specified resource. It returns a list of all available users/resources/products in the server.N.B you cannot modify data using GET request. We will do this in two ways: getting all users and getting a specific user.

Get All Users

Step 1:

Create an action(get users action). Update your action class with this action.

export const getUsers = (users) => {
return {
type: ActionTypes.GET_USERS,
payload: users
}
}

Step 2:

Create action creator function for getting all users from the API by making an API GET request.

/// fetch all users 
export const getUsersAction = () => {
return (dispatch) => {
axios.get('https://your endpoint')
.then(response => {
console.log(response);
/// dispatch function dispatches an action which triggers state changes in the store
dispatch(getUsers(response.data)
);
})
.catch(error => {
console.log(error);
});
}
}

Step 3:

Update the reducer switch statement with the action creator function.

case ActionTypes.GET_USERS:
//the three dots are ES6 syntax,creates a copy of an object
return {
///make a copy of `state`
...state,
/// update the copy with the new value
users: action.payload, loading: false
}

Step 4:

Update the UI with the action creator method. I have included pagination and search and filter in this page. If you don’t need that just remove the slice and filter function to look like below. N.B I have included the delete user in this page which is covered down in the delete request. Implement the delete request for this part to work.

users.map((user)=>

GET a single user

Step 1:

Create get user action

export const getUser = (user) => {
return {
type: 'GET_USER',
payload: user
}
}

Step 2:

Create action creators which makes an API GET(id) request.

/// fetch data of a single user  basedin id
export const getUserAction = (id) => {
return (dispatch) => {
axios.get(`https://your endpoint${id}`)
.then(response => {
console.log(response);
dispatch(getUser(response.data)
);
})
.catch(error => {
console.log(error);
});
}
}

Step 3:

Update the reducer

case ActionTypes.GET_USER:
return {
...state,
user: action.payload
}

Step 4:

Update the UI to display user detail, one user detail.

N.B user id should be unique

Delete Request

It is used to delete an item/user/product using the specified URL

Step 1:

Create an action to delete a user

export const deleteUser = () => {
return {
type: ActionTypes.DELETE_USER,
}
}

Step 2:

Create a creator function to call the delete API

/// delete a user
export const deleteUserAction = (id) => {
return (dispatch) => {
axios.delete(`https://your url/${id}`)
.then(response => {
console.log(response);
dispatch(deleteUser());
dispatch(getUsersAction());
})
.catch(error => {
console.log(error);
});
}
}

Step 3:

Update the reducers

case ActionTypes.DELETE_USER:
return { ...state }

Step 4:

Update the UI. This is done in the get all users UI.

Follow this repo for clarification GITHUB

SAMPLE SITE CREATED WITH REDUX-CRUD

HAPPY CODING!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

--

--

Mercy Jemosop
Mercy Jemosop

Written by Mercy Jemosop

Software Developer. I am open to job referrals. connect with me on twitter @kipyegon_mercy

No responses yet