Skip to content

Potential mistake in useEffect in todo-app example? #1

Description

@nikelborm

const loadTodos = () => {
console.log(`loadTodos starting live query`)
db.extensions.live.query<Todo>("select * from todos order by text").then((todos) => {
try {
setTodos(todos.initialResults.rows)
const callback = (newTodos: LiveQueryResults<Todo>) => {
console.log(`live query todos got new rows`, newTodos.rows)
setTodos(newTodos.rows)
}
todos.subscribe(callback)
return () => todos.unsubscribe(callback)
} catch (e) {
console.error(`Error setting up live query for todos`, e)
}
})
}

Hi! Your project is very interesting to me and I think I want to write something fun using it. I was looking at the code and wanted to clarify a little thing. I know that devs can return cleanup function from useEffect, but what's confusing to me is that you return it from db.extensions.live.query asynchronous callback.

Did you mean to write something like this?

const loadTodos = () => {
	let unsubscriber: () => void = () => {};

	console.log(`loadTodos starting live query`)
	db.extensions.live.query<Todo>("select * from todos order by text").then((todos) => {
		try {
			setTodos(todos.initialResults.rows)
			const callback = (newTodos: LiveQueryResults<Todo>) => {
				console.log(`live query todos got new rows`, newTodos.rows)
				setTodos(newTodos.rows)
			}
			todos.subscribe(callback)
			unsubscriber = () => todos.unsubscribe(callback)
		} catch (e) {
			console.error(`Error setting up live query for todos`, e)
		}
	})
	return () => unsubscriber()
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions