action;
export const ON_MESSAGE = 'ON_MESSAGE';
export const sendMessage = (text, sender = 'user') => ({
type: ON_MESSAGE,
payload: { text, sender },
});
reducer:
import { ON_MESSAGE } from 'Redux/actions/Chat_action';
import { act } from 'react-dom/test-utils';
const initalState = [{ text: [] }];
const messageReducer = (state = initalState, action) => {
switch (action.type) {
case ON_MESSAGE:
return [...state, action.payload];
default:
return state;
}
};
export default messageReducer;
combine reducer:
import Chat from 'Redux/reducers/Chat_reducer';
export default combineReducers({
Chat,
});
store:
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './rootReducer';
export default function configureStore(initialState) {
return createStore(rootReducer, applyMiddleware(thunk));
}
and code:
const Chat = props => {
const dispatch = useDispatch();
const messages = useSelector(state => state.Chat);
const [text, setText] = React.useState('');
console.log(messages);
return (
<Styled.ChatBox>
<Styled.ChatHeader>
<p>Chat Bot</p>
<div>
<FontAwesomeIcon icon={faAngleDown} size="1x" color="white" />
<FontAwesomeIcon icon={faTimes} size="1x" color="white" />
</div>
</Styled.ChatHeader>
<Styled.ChatLog>
{messages.map(message => (
<Styled.ChatMessage>{message.text}</Styled.ChatMessage>
))}
</Styled.ChatLog>
<Styled.ChatInput>
<textarea
value={text}
onChange={e => setText(e.target.value)}
placeholder="Digite aqui sua mensagem"
/>
<button onClick={() => dispatch(sendMessage({ text }))}>
<FontAwesomeIcon icon={faPaperPlane} size="lg" color="black" />
</button>
</Styled.ChatInput>
</Styled.ChatBox>
);
};
basically my initial message appears normally in my chat body but when I type a message and use the dispatch I get the following errors:
Uncaught Error: Objects are not valid as a React child (found: object with keys {text}).
and
The above error occurred in the component:
the problem is here:
<Styled.ChatLog>
{messages.map(message => (
<Styled.ChatMessage>{message.text}</Styled.ChatMessage>
))}
</Styled.ChatLog>
[...state, ...action.payload]ON_MESSAGE, I think something with the way you add theaction.payloadis not right, that's why I suggested it. Does it help or you still get the same error?