'How to return id associated with data in redux store?

I want to globally maintain an array of messages using Redux.

type Message = { content: string, key: string }
type State = {
  messages: Message[]
}

const slice = createSlice({
  name: 'messages',
  initialState: { messages: [] },
  reducers: {
    addMessage: (state: State, action: PayloadAction<string>) => {
      const newMessage = action.payload;
      const newId = UUID();
      return {
        messages: [...state.messages, { content: newMessage, key: newId }]
      };
    },
    removeMessage: (state: State, action: PayloadAction<string>) => {
      const toBeRemovedId = action.payload
      // remove message associated with input ID from global state
    }
  }
});

The problem is that if I want to remove message, I need to provide ID of a message. Ideally, I want to return ID of newly added message from addMessage, but I am not sure if it's possible.

// want to return id here but returns action object
const messageId = dispatch(addMessage("new message"));
...
//do something
...
dispatch(removeMessage(messageId))

Adding id as a parameter of addMessage seems like a bad idea because ids should be internally managed by the storage. Thoughts?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source