obolus/www/pages/list.jsx

57 lines
1.6 KiB
React
Raw Normal View History

2019-05-23 14:55:02 +00:00
import React, { useEffect, useRef, useState } from 'react'
import { withAuthSync } from '../utils/auth'
import Layout from '../components/layout'
2019-05-24 13:26:22 +00:00
import { callAPI, useCallAPI } from '../utils/api'
import Item from '../components/item'
2019-05-23 14:55:02 +00:00
2019-05-24 13:26:22 +00:00
const List = ({ fetched }) => {
2019-05-23 14:55:02 +00:00
const input = useRef(undefined)
const [text, setText] = useState('')
2019-05-24 13:26:22 +00:00
const [data, refresh] = useCallAPI({ url: `/api/items` })
2019-05-23 14:55:02 +00:00
useEffect(() => {
if (!input.current) return
input.current.focus()
}, [input])
2019-05-24 13:26:22 +00:00
const _submit = () => callAPI(null, {
url: `/api/items/`,
method: 'post',
data: { text },
}).then(refresh)
const _clear = () => callAPI(null, {
url: `/api/items/`,
method: 'delete',
}).then(refresh)
2019-05-23 14:55:02 +00:00
2019-05-24 13:26:22 +00:00
const items = data || fetched
2019-05-23 14:55:02 +00:00
return <Layout>
2019-05-24 13:26:22 +00:00
<form onSubmit={_submit}>
2019-05-23 14:55:02 +00:00
<div className="input-group">
<input
type="text" className="form-input" placeholder="..." ref={input}
value={text} onChange={e => setText(e.target.value)}/>
<button type="submit" className="btn btn-primary input-group-btn">Add</button>
</div>
</form>
<br/>
<table className="table table-hover">
<tbody>
2019-05-24 13:26:22 +00:00
{items.map((item, i) => <Item key={i} {...item} refresh={refresh}/>)}
2019-05-23 14:55:02 +00:00
</tbody>
</table>
<br/>
2019-05-24 13:26:22 +00:00
<button onClick={_clear} className="btn btn-error">Delete All</button>
2019-05-23 14:55:02 +00:00
</Layout>
}
List.getInitialProps = async ctx => ({
2019-05-24 13:26:22 +00:00
fetched: await callAPI(ctx, { url: `/api/items` }),
2019-05-23 14:55:02 +00:00
})
export default withAuthSync(List)