my action:
export const ON_MESSAGE = 'ON_MESSAGE';
export const sendMessage = (text, sender = 'user') => ({
type: ON_MESSAGE,
payload: { text, sender },
});
my reducer:
const initalState = [{ text: [] }];
const messageReducer = (state = initalState, action) => {
switch (action.type) {
case ON_MESSAGE:
return [...state, action.payload];
default:
return state;
}
};
export default messageReducer;
my code:
const Chat = props => {
const dispatch = useDispatch();
const messages = useSelector(state => state.Chat);
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></Styled.ChatLog>
<Styled.ChatInput>
<textarea placeholder="Digite aqui sua mensagem" />
<button onClick={dispatch(sendMessage)}>
<FontAwesomeIcon icon={faPaperPlane} size="lg" color="black" />
</button>
</Styled.ChatInput>
</Styled.ChatBox>
);
};
export { Chat };
Hello basically i would like to know how i would send the value typed in my text to my redux store
and also how I would display this typed value in my component
> <Styled.ChatLog> </ Styled.ChatLog>
basically each message should generate a div (a component)
> <Styled.ChatMessage />
you can store your message in local state and send that to payload.
const Chat = props => {
const dispatch = useDispatch();
const messages = useSelector(state => state.Chat);
const [text, setText] = React.useState("");
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>
);
};
export { Chat };
i got this error on <button onClick={dispatch(sendMessage({ text }))}>: Too many re-renders. React limits the number of renders to prevent an infinite loop.
updated answer, you need to create arrow function there () => dispatch(sendMessage( { text })
Thanks bro could you help me what better way to show the typed messages in my ChatMessage component on chatlog
you can map over your messages and render your ChatMessage component. I updated my answer. please check
i got this error : × Error: Objects are not valid as a React child (found: object with keys {text}). If you meant to render a collection of children, use an array instead.