Skip to content

[React] Using Telefunc for initial SSR data (like Next.js's Server Actions) #102

@brillout

Description

@brillout

Currently, Telefunc cannot be used for fetching the initial data of a page. (You have to use something like Vike's +data hook instead.)

Workarounds

If you use vike-react-query, then see vike-react-query > Usage with Telefunc.

You can use Telefunc with the useAsync() component hook of react-streaming. (If you use vike-react, vike-react already installs react-streaming.)

But getContext() doesn't work (yet) with these approaches (see also vikejs/vike-react#98).

Design

useData

// TodoItem.tsx

import { useData } from 'telefunc/react'
import { onLoadTodoItem } from './TodoItem.telefunc.ts'

function TodoItem() {
  const data = useData(
    () => onLoadTodoItem(id),
    // Dependency array like useEffect()
    [id]
  )
  return <>
    <span>{data.text}</span>
  </>
}

Alternative design:

// TodoItem.tsx

import { useData } from 'telefunc/react'
import { onLoadTodoItem } from './TodoItem.telefunc.ts'

function TodoItem() {
  // No need to pass a dependency array!
  const data = useData(onLoadTodoItem)(id)
  return <>
    <span>{data.text}</span>
  </>
}

See also:

useDataState

// MovieList.tsx

import { useDataState } from 'telefunc/react'
import { onMovieFetch } from './MovieList.telefunc.ts'

function MovieList() {
  return (
    <div>
      <p>List of movies:</p>
      <Suspense fallback={<p>Loading...</p>}>
        <List />
      </Suspense>
    </div>
  )
}

function List() {
  // Similar to useState
  const [movies, setMovies] = useDataState(
    // Async Initial data
    async () => await onMovieFetch(),
    // Dependency array like useEffect()
    []
  )
  return (
    <ul>
      {movies.forEach((movie) => (
        <li>{movie.title} ({movie.release_date})</li>
      ))}
      <button onClick={async () => setMovies(await onMovieFetch())}>
        Refetch
      </button>
    </ul>
  )
}

PoC

There is also an integration with react-streaming built directly into Telefunc, but it isn't ready for public usage yet and breaking change will occur.

Warning

You can play around with it at /examples/react-streaming. But you're warned: the API as it is today will be deprecated.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions