Warm tip: This article is reproduced from stackoverflow.com, please click
reactjs redux

React / Redux / Send text typed on textarea to the store

发布于 2020-04-08 09:43:06

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 />
Questioner
user12356906
Viewed
23
Amit Chauhan 2020-01-31 21:13

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 };