Skip to content

Instantly share code, notes, and snippets.

@omas-public
Last active February 16, 2024 08:36
Show Gist options
  • Save omas-public/1d7ba30f8c009f96d97676c64d012bbc to your computer and use it in GitHub Desktop.
Save omas-public/1d7ba30f8c009f96d97676c64d012bbc to your computer and use it in GitHub Desktop.
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