Ogen
Ogen

Reputation: 6709

Using Redux to display a notification in response to a network request

My web application uses React and Redux and UIKit. It consists of screens A and B.

Screen A contains a button which - upon pressing - will send an asynchronous network request to post some data to a server.

If a user remains on screen A until a response returns from the server, they will receive confirmation about whether or not the request was successful.

The way I have implemented this using React and Redux is by having a component which is responsible for displaying a confirmation banner. This component listens to changes to a state called postStatus in my Redux store. When the user clicks on the button, 3 Redux actions with statuses PENDING, SUCCESS and ERROR are potentially dispatched. After they are dispatched - they are caught by the reducers which change the postStatus state accordingly. This state then gets mapped to my components properties and it is re-rendered to display a relevant banner.

However, if the user does not remain on screen A until a response returns from the server and navigates to screen B instead - I would like a notification to show up so the user is still aware of the status of the request.

My question is, what would be the most sensible way to implement this behaviour?

Here are a couple of things I can think of:

  1. Create a react component that doesn't actually render anything - it just listens to postState and some extra piece of state that represents which screen the user is on. Implement the componentWillReceiveProps react lifecycle method and if the postState is SUCCESS or ERROR and the other state says that the user is on not on screen A - then call UIKit.notify() to show the notification.
  2. Call UIKit.notify() when dispatching the SUCCESS or ERROR action if the user is not on screen A.
  3. Call UIKit.notify() when reducing the state after being dispatched the SUCCESS or ERROR action if the user is not on screen A.

There are most likely a lot of other solutions so I'm keen to hear some.

Upvotes: 2

Views: 2028

Answers (1)

gyosifov
gyosifov

Reputation: 3223

I know I am late for the answer, but I stumbled upon this myself so here is what I did.

The way I look at it is that the temporary notification is an application side effect. In my project I am using redux-saga, but you can achieve this using any other side effects library.

The code (using deleting an user as an example):

...
function* deleteUserSuccess(action) {
    yield call(message.success, 'Successful deletion!');
}

const watchDeleteUserSuccess = function* () {
    yield takeEvery(types.DELETE_USER_SUCCESS, deleteUserSuccess);
}
...

PROS: It is readable and it works.

CONS: The only downside that I see is that you make your sagas know about your UI library. But you can wrap it in a separate function/file/module to abstract the saga from it.

Upvotes: 1

Related Questions