Last active
February 16, 2024 08:36
-
-
Save omas-public/1d7ba30f8c009f96d97676c64d012bbc to your computer and use it in GitHub Desktop.
This file contains 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 { useState, useRef, useEffect } from 'react' | |
const Chat = () => { | |
const refInput = useRef('') | |
const [messages, setMessages] = useState(null) | |
useEffect(() => { | |
const json = localStorage.getItem('chat') ?? '[]' | |
setMessages(JSON.parse(json)) | |
}, []) | |
useEffect(() => { | |
if (messages.length === 0) return | |
const json = JSON.stringify(messages) | |
localStorage.setItem('chat', json) | |
}, [messages]) | |
const handleSubmit = e => { | |
const text = refInput.current.value | |
setMessages(p => [text, ...p]) | |
refInput.current.value = '' | |
refInput.current.focus() | |
} | |
return ( | |
<> | |
<input type='text' ref={refInput} /> | |
<button onClick={handleSubmit}>click</button> | |
<ul> | |
{messages.map((message, i) => ( | |
<li key={i}>{message}</li> | |
))} | |
</ul> | |
</> | |
) | |
} | |
export default Chat |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment