Skip to content

How to fetch data again? #14

@ftzi

Description

@ftzi

Let's say an error happened while loading all docs in a collection with useAll, like the internet went off, or I just want to fetch the new data (without useOnX). In my ScrollView, I have a refreshControl. How can I fetch the data again?

The current code of useAll is

export default function useAll<Model>(
  collection: Collection<Model>
): TypesaurusHookResult<Doc<Model>[] | undefined> {
  const [result, setResult] = useState<Doc<Model>[] | undefined>(undefined)
  const [error, setError] = useState<unknown>(undefined)
  const loading = result === undefined && !error

  const deps = [JSON.stringify(collection)]
  useEffect(() => {
    if (result) setResult(undefined)
    all(collection).then(setResult).catch(setError)
  }, deps)

  return [result, { loading, error }]
}

What I could do is on refresh set collection to null, ignore the error if collection is null, and useEffect on the error and if the collection is null, change collection to the original value.

Logically seems to work but it's quite ugly. Do you have a better idea for it?

Maybe I will create my custom useAll, that exposes a refresh prop function that just calls all(collection).then(setResult).catch(setError)

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