import { useEffect, useState } from "react";
import { ulid } from "ulid";
import { createClient } from '@supabase/supabase-js'
const supabase = createClient(import.meta.env.VITE_SUPABASE_URL, import.meta.env.VITE_SUPABASE_PUB_KEY)
export const App = () => {
const [hoge, setHoge] = useState('');
const [piyo, setPiyo] = useState(0);
const [hogeList, setHogeList] = useState([]);
const [error, setError] = useState("");
const [isLoading, setIsLoading] = useState(true);
const onChangeHoge = (e) => {
setHoge(e.target.value)
}
const onChangePiyo = (e) => {
setPiyo(e.target.valueAsNumber)
}
const addHoge = () => {
if (hoge === '' || piyo <= 0 || piyo === '') return;
const newHoge = { id: ulid(), hoge, piyo };
const newHogeList = [...hogeList, newHoge];
setHogeList(newHogeList);
setHoge('');
setPiyo(0);
}
useEffect(() => {
supabase.from('hoge_table').select('*')
.then((response) => {
setHogeList(response.data)
setIsLoading(false)
})
}, [])
return isLoading ? <p>読み込み中...</p> : (
<>
<h1>hogeリスト</h1>
{error && <p style={{ color: 'red' }}>{error}</p>}
<div>
<label htmlFor="hoge">hoge: </label>
<input type="text" id="hoge" name="hoge" value={hoge} onChange={onChangeHoge} />
</div>
<div>
<label htmlFor="piyo">piyo: </label>
<input type="number" id="piyo" name="piyo" value={piyo} onChange={onChangePiyo} />
</div>
<div>
<p><span>入力されているhoge: </span>{hoge}</p>
</div>
<div>
<p><span>入力されているpiyo: </span>{piyo ? piyo : 0}</p>
</div>
<div>
<button onClick={addHoge}>登録</button>
</div>
<ul>
{hogeList.map((item) => {
const { id, hoge, piyo } = item;
return (<li key={id}>{hoge}: {piyo}</li>)
})}
</ul>
</>
)
}