`useLiveQuery` needs a default value.
Currently, useLiveQuery returns undefined until the initial query has returned. This leads to a bunch of if results !=== undefined checks in your component code.
For example:
function Component() {
const results = useLiveQuery(`
SELECT * FROM items
WHERE foo = $1
`, ['bar'])
const items = results !== undefined ? results.rows : []
// ...
Now, if you look at useState, it avoids this by supporting a default value:
function Component() {
const [results, setResults] = useState([])
// ...
I propose the ergonomic improvement of supporting a default value with useLiveQuery:
function Component() {
const { rows: items } = useLiveQuery(`
SELECT * FROM items
WHERE foo = $1
`, ['bar'], [])
// ...
Using a third positional argument for it is slightly tricky with query parameters (hence cherry picking an example of a query that uses parameters), because then you need to specify the query parameters arg even if not using them. I guess an alternative would be a {default: value} option (more explicit but also more verbose).
an alternative would be a {default: value} option (more explicit but also more verbose).
I think it's ok to be more verbose when you need that option. If we default to [] I guess would be fine for most users.
I think any default value should be explicit. It's useful, when you want to, to be able to distinguish between empty results and no results yet.
const items = results !== undefined ? results.rows : []
const items = results?.rows ?? []
The live.query() api excepts both optional arguments of a single options object arguments:
https://github.com/electric-sql/pglite/blob/0c7454d1cef9725c6dc3f1e26352016c6145c3be/packages/pglite/src/live/interface.ts#L29-L51
useLiveQuery also has multiple call signatures:
https://github.com/electric-sql/pglite/blob/0c7454d1cef9725c6dc3f1e26352016c6145c3be/packages/pglite-react/src/hooks.ts#L101-L112
although not a option arg one. Maybe we should add that.