0

I am learning react-redux at the moment, already grasped the basics (I believe), I am now trying to create a notification array on my state that can be populated by several actions.

But since is a notification, I only want to add a notification after each of those actions is completed (the state is changed).

I thought about using a middleware class but that would add the notification into array before the action is computed on the reduce.

Quick example:

User logins -> dispatch action -> affects state property related to login -> adds a notification on the notification array

User adds item -> dispatch action -> affects state property related to items -> adds a notification on the notification array

These are 2 different actions, I could in the if logic of each action (on reducer) update the notification array, but seems like repeated code and I would be creating notification object on a reducer, is that okay?

So in this case where should I dispatch the action of adding a notification to the notification array?

I am looking for best practices

1 Answer 1

1

The best practice is to handle such scenario's in reducer. Process the data one-time and update state accordingly. In your scenario, you want to update the notifications array once the action is completed. You have to do that repeatedly because it is to be done. Here is what you can do:

case LOGIN:
  //checks if user is valid
  return {
     ...state
     loggedIn: true,
     user,
     notifications: state.notification.push({ id: 1, message: "Logged In!" })
  }

And if you want to remove a notification you can do that:

case REMOVE_NOTIFICATION:
  // You can get the notification ID you want to remove from action
  let notifications = state.notification.filter(notify => notify.id !== action.id);
  return {
     ...state
     notifications
  }

Hope this will help you.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, fair enough yeah. I was thinking more deep into this, and I will have problems deleting the notifications from the array, I could use for id an hash for the message but the message will be the same, how can I overcome this? on my UI I will have several popups of notifications with a close button, and I need to correctly identify which one I am deleting from the state according to the one I am clicking, makes sense?
@TiagoM Answer Updated
Yes I understand that, but how do I the define the id for the notifcations on notification creation? use a random number?
nevermind, I can store in the redux state another variable initialize to zero and increment on each notification add, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.