1

I am trying to generate a unique key for each new notification. Each notification needs a unique key for tracking purposes, i.e. closing the notification. When I attempt to generate a random key, the key is only being generated once and is then used for multiple actions, instead of a unique key per action.

I have tried generating the key within the action creator, as well as within the corresponding epic. If I could generate the key in the action creator, that would be ideal but I'm not sure if that is possible.


// Action generator.
export const postNotification = (notification: NotificationPostProps): DataAction<Notification, POST_NOTIFICATION> => ({
    type: POST_NOTIFICATION,
    payload: {
        ...notification,
        dismissed: false,
    },
});

// Epic listening for password change errors.
const onPasswordChangeError: Epic = action$ =>
    action$.pipe(
        ofType(error(CHANGE_PASSWORD)),
        mapTo(
            postNotification({
                type: 'error',
                message: 'Incorrect password provided.',
                // @ts-ignore
                key: new moment().unix() + Math.random(), // Attempt at generating a unique key.
            }),
        ),
    );

Each notification should have a unique key, however, the logs show a different story.

// First action.

{
   type: "app/POST_NOTIFICATION", 
   payload: {
      dismissed: false,
      key: 1564243314.8857393, // These should be unique.
      message: "Incorrect password provided.",
   }
}

// Second action
{
   type: "app/POST_NOTIFICATION", 
   payload: {
       dismissed: false,
      key: 1564243314.8857393, // These should be unique.
      message: "Incorrect password provided.",
   }
}
Flash619
  • 21
  • 1
  • 3
  • Check this: https://stackoverflow.com/q/43837659/1383932 – fiveelements Jul 27 '19 at 16:17
  • @fiveelements That covers generating a UUID very well. However that would still fall victim to the same issue as it would be generated once and stored within an object within the epic. – Flash619 Jul 27 '19 at 16:23
  • 2
    Use `map(() => postNotification(/* ... */))` instead of `mapTo(postNotification(/* ... */)))`. The `postNotification` call in the latter is made only once - when the epic is created - it isn't called for each action notification. – cartant Jul 28 '19 at 02:43

0 Answers0