Redux state management for different request methods

Here I have described ways to manage state using redux for GET, POST, PATCH & DELETE

Bismita Guha
AnitaB.org Open Source
2 min readJul 13, 2020

--

Redux is used for state management in JavaScript applications, which can be changed during the lifecycle of the application. It can be easily used with actions and reducers. So a basic problem which we might have observed in the basic stages of learning redux is that on adding an element to the backend of our application only the API for creating the object is called and the general list of objects still remains as it is. You need to make another call to the GET endpoint to retrieve the new list.

Making so many API calls doesn’t give efficient performance in your application, and also prevents a dynamic application. Here, by the simple use of reducers, we can handle the state while implementing different request methods.

Check out the official documentation of Redux for more insight…

Initial States

In every reducer, we pass the action to be performed and the initial state. So define an initial state for everything you need. For now you can use 2 states to understand the concept:

const initialState = {
list: [],
postobject: []
}

One for receiving the GET data, and another for creating a new object in the same list.

GET method

This is the simplest one.

You always need to define the default method like in every switch method.

POST method

comma is used to append. So action.payload gets appended to the previous state of list . Now without retrieving the new list, we have updated the frontend.

DELETE method

Now the object needs to be deleted from the list. So, we are actually sending the id of the object in the action.payload . We have to remove the object whose id is equal to action.payload .

PATCH method

PATCH is kind of a combination of DELETE and POST methods. We have to remove the object which is getting updated and replace it with the action.payload , which contains the updated data.

First, we are removing the old object using it’s id , and then appending the new data to the list.

This simple implementation reduces much of the complicated code which might get involved. Happy Developing!

--

--