npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

vike-react-query

v0.1.3

Published

<!-- WARNING: keep links absolute in this file so they work on NPM too -->

Downloads

2,556

Readme

npm version

vike-react-query

Enables your React components to fetch data using TanStack Query. Powered by HTML streaming.

[!NOTE] Includes:

Installation
Basic usage
withFallback()
<head> tags
Error Handling
Settings
Usage with Telefunc
How it works
Version history
See also

Installation

  1. npm install @tanstack/react-query vike-react-query
  2. Extend +config.js:
    // pages/+config.js
    
    import vikeReact from 'vike-react/config'
    import vikeReactQuery from 'vike-react-query/config'
    
    export default {
      // ...
      extends: [vikeReact, vikeReactQuery]
    }

[!NOTE] The vike-react-query extension requires vike-react.

Basic usage

import { useSuspenseQuery } from '@tanstack/react-query'

const Movie = ({ id }) => {
  const result = useSuspenseQuery({
    queryKey: ['movie', id],
    queryFn: () =>
      fetch(`https://brillout.github.io/star-wars/api/films/${id}.json`)
      .then((res) => res.json())
  })

  const { title } = result.data

  return (
    <div>
      Title: <b>{title}</b>
    </div>
  )
}

[!NOTE] Even though useSuspenseQuery() is imported from @tanstack/react-query, you need to install vike-react-query for it to work. (The useSuspenseQuery() hook requires an HTML stream integration.)

withFallback()

withFallback(Component) // Use default loading fallback (see +Loading)
withFallback(Component, Loading) // Define loading fallback
withFallback(Component, Loading, Error) // Define loading and error fallback
withFallback(Component, undefined, Error) // Define error fallback
// Movie.tsx

import { useSuspenseQuery } from '@tanstack/react-query'
import { withFallback } from 'vike-react-query'

const Movie = withFallback(
  ({ id }: { id: string }) => {
    const result = useSuspenseQuery({
      queryKey: ['movie', id],
      queryFn: () =>
        fetch(`https://brillout.github.io/star-wars/api/films/${id}.json`)
        .then((res) => res.json())
    })

    const { title } = result.data

    return (
      <div>
        Title: <b>{title}</b>
      </div>
    )
  },
  ({ id }) => <div>Loading movie {id}</div>,
  // The props `retry` and `error` are provided by vike-react-query
  // Other props, such as `code`, are provied by the parent component
  ({ id, retry, error }) => (
    <div>
      Failed to load movie {id}
      <button onClick={() => retry()}>Retry</button>
    </div>
  )
)

+Loading

If you skip the Loading parameter, then a default loading component (provided by vike-react) is used. You can create a custom default loading component:

// pages/+Loading.jsx

export default { component: LoadingComponent }

function LoadingComponent() {
  // Applies on a component-level
  return <div>Loading...</div>
}

Instead of adding a loading fallback to the component, you can set a loading fallback to the page and layouts:

// pages/+Loading.jsx

export default { layout: LoadingLayout }

function LoadingLayout() {
  // Applies to the page and all layouts
  return <div>Loading...</div>
}

[!NOTE] The +Loading.layout setting is optional and only relevant when using useSuspenseQuery() without withFallback() or withFallback(Component, false).

withFallback(Component, false) // Don't set any loading fallback
withFallback(Component, undefined) // Use default loading fallback

Manual <Suspense> boundary

Technically speaking:

You can also manually add a <Suspense> boundary at any arbitrary position:

import { Suspense } from 'react'

function SomePageSection() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <SomeDataFetchingComponent />
      <SomeOtherDataFetchingComponent />
    </Suspense>
  )
}

<head> tags

To set tags such as <title> and <meta name="description"> based on fetched data, you can use <Config>, <Head>, and useConfig().

import { useSuspenseQuery } from '@tanstack/react-query'
import { Config } from 'vike-react/Config'
import { Head } from 'vike-react/Head'

function Movies() {
  const query = useSuspenseQuery({
    queryKey: ['movies'],
    queryFn: () => fetch('https://star-wars.brillout.com/api/films.json')
  })
  const movies = query.data
  return (
    <Config title={`${movies.length} Star Wars Movies`} />
    <Head>
      <meta name="description" content={`All ${movies.length} movies from the Star Wars franchise.`} />
    </Head>
    <ul>{
      movies.map(({ title }) => (
        <li>{title}</li>
      ))
    }</ul>
  )
}

Error Handling

From a UI perspective, the classic approach to handling errors is the following.

  • Show a 404 page, for example <h1>404 Page Not Found</h1><p>This page could not found.</p>.
  • Show an error page, for example <h1>500 Internal Server Error</h1><p>Something went wrong.</p>.
  • Redirect the user, for example redirecting the user to /publish-movie upon /movie/some-fake-movie-title because there isn't any movie some-fake-movie-title.

But because vike-react-query leverages HTML streaming these approaches don't work (well) and we recommend the following instead.

  • Show a not-found component, for example <p>No movie <code>some-fake-movie-title</code> found.</p>.
  • Show an error component, for example <p>Something went wrong (couldn't fetch movie), please try again later.</p>.
  • Show a link (instead of redirecting the user), for example <p>No movie <code>some-fake-movie-title</code> found. You can <a href="/publish-movie">publish a new movie</a>.</p>.

See: withFallback()

[!NOTE] HTML chunks that are already streamed to the user cannot be reverted and that's why page-level redirection (throw redirect) and rewrite (throw render()) don't work (well).

Also it isn't idiomatic: the whole idea of collocating data-fetching with the UI component is to think in terms of the component in isolation rather than in terms of the page.

Settings

You can modify the defaults defined by QueryClient.

// +config.js

export default {
  queryClientConfig: {
    defaultOptions: {
      queries: {
        staleTime: 60 * 1000
      }
    }
  }
}

You can access pageContext:

// +queryClientConfig.js

export default (pageContext) => ({
  defaultOptions: {
    queries: {
      staleTime: pageContext.data.staleTime,
      retry: pageContext.routeParams.userId ? true : false
    }
  }
})

[!NOTE] You can apply settings to all pages, a group of pages, or only one page. See Vike Docs > Config > Inheritance.

Usage with Telefunc

You can use vike-react-query with Telefunc.

[!NOTE] By using vike-react-query with Telefunc, you combine RPC with all TanStack Query features.

With Telefunc, the query function always runs on the server.

Query example

// movie.telefunc.ts

export async function getMovie(id: string) {
  const movie = await prisma.movie.findUnique({ where: id })
  return movie;
}
// movie.tsx

import { useSuspenseQuery } from '@tanstack/react-query'
import { withFallback } from 'vike-react-query'
import { getMovie } from './movie.telefunc'

const Movie = withFallback(
  ({ id }: { id: string }) => {
    const query = useSuspenseQuery({
      queryKey: ['movie', id],
      queryFn: () => getMovie(id)
    })

    const { title } = query.data

    return (
      <div>
        Title: <b>{title}</b>
      </div>
    )
  },
  ({ id }) => <div>Loading movie {id}</div>,
  ({ id, retry }) => (
    <div>
      Failed to load movie {id}
      <button onClick={() => retry()}>Retry</button>
    </div>
  )
)

Mutation example

// movie.telefunc.ts

export async function createMovie({ title }: { title: string }) {
  const movie = await prisma.movie.create({ data: { title } })
  return movie
}
// movie.tsx

import { useMutation } from '@tanstack/react-query'
import { createMovie } from './movie.telefunc'

const CreateMovie = () => {
  const ref = useRef<HTMLInputElement>(null)
  const mutation = useMutation({
    mutationFn: createMovie
  })

  const onCreate = () => {
    const title = ref.current?.value || 'No title'
    mutation.mutate({ title })
  }

  return (
    <div>
      <input type="text" ref={ref} />
      <button onClick={onCreate}>Create movie</button>
      {mutation.isPending && 'Creating movie..'}
      {mutation.isSuccess && 'Created movie ' + mutation.data.title}
      {mutation.isError && 'Error while creating the movie'}
    </div>
  )
}

Putting it together

// movie.telefunc.ts

export async function getMovies() {
  const movies = await prisma.movie.findMany()
  return movies;
}
export async function createMovie({ title }: { title: string }) {
  const movie = await prisma.movie.create({ data: { title } })
  return movie
}
// movie.tsx

import { useSuspenseQuery, useMutation } from '@tanstack/react-query'
import { withFallback } from 'vike-react-query'
import { getMovies, createMovie } from './movie.telefunc'

const Movies = withFallback(
  () => {
    const queryClient = useQueryClient()
    const query = useSuspenseQuery({
      queryKey: ['movies'],
      queryFn: () => getMovies()
    })
    const mutation = useMutation({
      mutationFn: createMovie,
      onSuccess() {
        query.invalidateQueries({ queryKey: ['movies'] })
        // or query.refetch()
      }
    })

    const ref = useRef<HTMLInputElement>(null)
    const onCreate = () => {
      const title = ref.current?.value || 'No title'
      mutation.mutate({ title })
    }

    return (
      <div>
        {query.data.map((movie) => (
          <div>Title: {movie.title}</div>
        ))}

        <div>
          <input type="text" ref={ref} />
          <button onClick={onCreate}>Create movie</button>
          {mutation.isPending && 'Creating movie..'}
          {mutation.isSuccess && 'Created movie' + mutation.data.title}
          {mutation.isError && 'Error while creating the movie'}
        </div>
      </div>
    )
  },
  <div>Loading movies</div>,
  ({ retry }) => (
    <div>
      Error while loading movies
      <button onClick={() => retry()}>Retry</button>
    </div>
  )
)

How it works

Upon SSR, the component is rendered to HTML and its data loaded on the server-side. On the client side, the component is merely hydrated.

Upon page navigation (and rendering the first page if SSR is disabled), the component is rendered and its data loaded on the client-side.

[!NOTE] With vike-react-query you fetch data on a component-level instead of using Vike's data() hook which fetches data on a page-level.

[!NOTE] Behind the scenes vike-react-query integrates TanStack Query into the HTML stream.

See also