In Redux, I currently have a state that looks something like the following.
{
activeConversation: "Jim"
conversations: (7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}]
user: {id: 8, username: "josh", email: ""}
}
I currently have a function that adds a new message to the conversations array. Here's how it works; it starts by calling it in thunk
.
export const postMessage = (body) => async (dispatch) => {
try {
if (!body.conversationId) {
dispatch(addConversation(body.recipientId, data.message));
} else {
dispatch(setNewMessage(data.message));
}
} catch (error) {
console.error(error);
}
};
If the conversationId
exists then it calls setNewMessage
in Actions
.
const SET_MESSAGE = "SET_MESSAGE";
export const setNewMessage = (message, sender) => {
return {
type: SET_MESSAGE,
payload: { message, sender: sender || null },
};
};
const reducer = (state = [], action) => {
switch (action.type) {
case SET_MESSAGE:
return addMessageToStore(state, action.payload);
default:
return state;
}
};
export default reducer;
The problem is that the state in this action only contains the conversations array and not anything else. What I need is to also have the activeConversation
so I can use it in my reducer function. I'm not quite sure how states work so I don't know why only the conversations array appears in state
and not anything else.
Also, here's how activeConversation
is being set.
const SET_ACTIVE_CHAT = "SET_ACTIVE_CHAT";
export const setActiveChat = (username) => {
return {
type: SET_ACTIVE_CHAT,
username
};
};
const reducer = (state = "", action) => {
switch (action.type) {
case SET_ACTIVE_CHAT: {
return action.username;
}
default:
return state;
}
};
I'm wondering how I can get the activeConversation
state for my set message reducer function.