Edgar Chirivella
Edgar Chirivella

Reputation: 13

Creating Redux actions for API calls that don't modify the state directly

We are developing a React application using Redux to manage the state. In general, Redux serves us well, but in one part of the application, we are using WebSockets to update our app state to allow all the connected users to have the most recent version of the data.

It looks like this: https://i.sstatic.net/uNAsk.png

In a regular Redux application, we would have 3 actions: ACTION_LOADING, ACTION_SUCCESS and ACTION_FAILURE to handle HTTP requests. In this case, the state is updating automatically after receiving new data from the WebSocket.

Is it correct to have a Redux action (thunk) to post this data to the server even if it does not modify the state, or is it better to call the service without using Redux in these cases?

In case we create actions, what pattern would you recommend?

Thank you.

Upvotes: 1

Views: 423

Answers (1)

rmlockerd
rmlockerd

Reputation: 4126

I would recommend wrapping it in a thunk for a couple of reasons:

  1. There's nothing fatal about initiating an action that doesn't end up mutating state (for whatever reason).
  2. Even if you aren't doing anything in the case of a successful POST (since all the action will come later via a message from the server), you still might need to dispatch an actions in case the POST fails for some reason.
  3. It allows your components to use one consistent mechanism (action dispatch) rather than sometimes one way and sometimes another.

Upvotes: 0

Related Questions