0206.md
const data = JSON.stringify([{ id: 1, name: 'hoge' }])
localStorage.setItem('test1', data)
localStorage.test2 = data
const test1 = localStorage.getItem('test1')
const test2 = localStorage.test2
console.log(test1.at(0).name)
console.log(JSON.parse(test2).at(0).name)
'use client'
import { useState, useEffect } from 'react'
const useLocalStorage = (key, initial) => {
const localSto
const initialState = JSON.parse(localStorage.getItem(key))
const [value, setValue] = useState(initialState ?? initial)
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value))
}, [value])
const setValues = newValue => {
setValue(newValue)
}
return [value, setValues]
}
export { useLocalStorage }
'use client'
import { useRef } from 'react'
import { useLocalStorage } from '../_lib/useLocalStorage'
import { v4 as uuidv4 } from 'uuid'
const Home = () => {
const [items, setItems] = useLocalStorage('items', [])
const inputRef = useRef('')
const handleClick = () => {
const newItem = { id: uuidv4(), text: inputRef.current.value }
setItems([newItem, ...items])
inputRef.current.value = ''
}
const handleDelete = e => {
console.log(e.target.parentElement.id)
setItems(prev => prev.filter(item => item.id != e.target.id))
}
return (
<>
<input type='text' ref={inputRef} />
<button onClick={handleClick}>button</button>
<ul>
{items.map(({ id, text }) => (
<li key={id} id={id}>
{text}
<button onClick={handleDelete}>delete</button>
</li>
))}
</ul>
</>
)
}
export default Home