pglite icon indicating copy to clipboard operation
pglite copied to clipboard

`useLiveQuery` needs a default value.

Open thruflo opened this issue 10 months ago • 4 comments

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).

thruflo avatar Feb 17 '25 08:02 thruflo

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.

tdrz avatar Feb 17 '25 09:02 tdrz

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.

thruflo avatar Feb 17 '25 10:02 thruflo

const items = results !== undefined ? results.rows : []

const items = results?.rows ?? []

tdrz avatar Feb 17 '25 10:02 tdrz

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.

samwillis avatar Feb 17 '25 13:02 samwillis