Skip to content

Best practice for returning undefined data #7020

Answered by TkDodo
robingenz asked this question in Q&A
Discussion options

You must be logged in to vote

if you want the query go to into error state when the item does not exist, you can check and throw a custom error as the answer by @riccardoperra shows.

if you're fine with having no data for a successfully resolved query, I'd just transform to null because that is allowed:

public getTaskById(
    id: string,
  ): Result<QueryObserverResult<Task | null, Error>> {
    return this.#query({
      queryKey: ['tasks', id],
      queryFn: async () => {
        const task = this.tasksService.getTaskById(id)
        return task ?? null
      }
    });
  }

of course you could also change getTaskById to already return null.

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by robingenz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants