Created
February 6, 2025 01:06
-
-
Save matthewoestreich/7c2383ca5dc37128bf71f35d81378cbc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useReducer, useState } from 'react'; | |
interface Message { | |
from: string; | |
message: string; | |
} | |
interface ChatState { | |
messages: Message[] | null; | |
} | |
type ChatStateAction = | |
| { type: "SENT_MESSAGE", payload: Message }; | |
function chatReducer(state: ChatState, action: ChatStateAction): ChatState { | |
switch(action.type) { | |
case "SENT_MESSAGE": | |
return { ...state, messages: [...(state.messages ?? []), action.payload] } | |
default: | |
return state; | |
} | |
} | |
const initialState: ChatState = { | |
messages: null | |
} | |
export default function App() { | |
const from = "Mike"; | |
const [messageText, setMessageText] = useState(""); | |
const [state, dispatch] = useReducer(chatReducer, initialState); | |
function handleInput(e) { | |
setMessageText(e.target.value); | |
} | |
function handleSendMessage() { | |
setMessageText(""); | |
dispatch({ type: "SENT_MESSAGE", payload: { from, message: messageText } }); | |
} | |
return ( | |
<div className='App'> | |
<div style={{height:"400px", width: "400px", backgroundColor: "white"}}> | |
<ul>{state.messages?.map((msg, index) => ( | |
<div key={index}> | |
<p>{msg.from}</p> | |
<p>{msg.message}</p> | |
</div> | |
))}</ul> | |
</div> | |
<input onChange={handleInput} value={messageText} type="text" /> | |
<button onClick={handleSendMessage}>Send Message</button> | |
</div> | |
); | |
} | |
// Log to console | |
console.log('Hello console'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment