I am new to react redux. I am trying to create a watson based chatbot using react and redux. My nodejs backend linked to watson api is working fine. However, I am bit confused in how to handle user and bot messages in front end side?
On component did mount, I dispatch the action to my backend and then I get the response from Watson and state is updated accordingly. First time, I only send an empty string to backend. When user press the send message button with his message. Action gets triggered again. I am using redux thunk to do async operation. when I get a response from my backend then, I dispatched that action with type "SEND_USER_MSG_TO_SOE" & payload. Now i have to send previous response which is stored in state + new input text to backend to get new response.
In my reducer, I am doing something like this [...state, action.payload]. Now it is overriding the input value of previous response as well. Could you please explain.
I need input and output message in array. So that I can use map and show it in as list.
Another thing, If I don't return [...state, action.payload] and send only payload. Then I left with only one response. How can I create array out of it with previous response input and output?
I am attaching Picture of Response. Please guide me
Thanks Meet
reducer:
export default (state = [], action) => {
console.log('reducer payload ---> ', action.payload);
switch(action.type) {
case 'SEND_USER_MSG_TO_SOE':
return [...state, action.payload]
default:
return state;
}
}
export default combineReducers({
watsonResponse: converReducer
})
action:
export const sendMessage = (userInput) => {
return async (dispatch, getState) => {
let response = null;
if (userInput === undefined) {
response = await axios.post('http://localhost:8014/message_in', userInput);
} else {
let newInput = [...getState().watsonResponse];
newInput[newInput.length - 1].input.text = userInput;
response = await axios.post('http://localhost:8014/message_in', newInput[newInput.length - 1]);
}
dispatch({
type: "SEND_USER_MSG_TO_SOE",
payload: response.data
});
}
}