Saltar al contenido principal

useFetch()

Obtiene un Endpoint si no está en la caché o está obsoleto. Devuelve un thenable que funciona con React.use(): use(useFetch(endpoint, args)) funciona como useSuspense(), suspende mientras los datos se cargan, devuelve los datos desnormalizados cuando están disponibles y vuelve a suspender tras una invalidación.

Uso​

Carga de datos en paralelo​

Como useFetch() y use() son llamadas separadas, varios fetches se inician en paralelo, incluso cuando el primer use() suspende. Consulta el ejemplo de fetches en paralelo más abajo.

import { use } from 'react';
import { useFetch } from '@data-client/react';
import { PostResource, CommentResource } from './Resources';

function PostWithComments({ id }: { id: number }) {
  // Both fetches start in parallel
  const postPromise = useFetch(PostResource.get, { id });
  const commentsPromise = useFetch(CommentResource.getList, {
    postId: id,
  });

  // use() reads the results — if the first suspends,
  // the second fetch is already in-flight
  const post = use(postPromise);
  const comments = use(commentsPromise);

  return (
    <article>
      <h3>{post.title}</h3>
      <p>{post.body}</p>
      <h4>Comments</h4>
      {comments.map(comment => (
        <div key={comment.id} className="listItem">
          <strong>{comment.author}</strong>: {comment.text}
        </div>
      ))}
    </article>
  );
}
render(<PostWithComments id={1} />);
Resultado
Store▶

Precarga​

useFetch() también se puede usar de forma independiente para asegurar que los recursos estén disponibles temprano en el árbol de renderizado, antes de que se necesiten.

consejo

Úsalo junto con un hook de enlace de datos (useCache(), useSuspense(), useDLE(), useLive()) en otro componente.

import { useFetch } from '@data-client/react';
import { PostResource } from './resources/Post';

function MasterPost({ id }: { id: number }) {
useFetch(PostResource.get, { id });
// ...
}

Comportamiento​

Estado de caducidadFetchComportamiento de use()resolvedCondiciones
Inválidosí1suspendefalseno está en el store, eliminación, invalidación
Obsoletosí1suspendefalse(primer render, cambio de args) & caducidad < ahora
Válidonodevuelve los datostruefetch completado
Errornolanza el errortrueel fetch falló, capturado por un Error Boundary
noundefinedse usó null como segundo argumento

Cuando el store se actualiza (p. ej., mediante mutaciones o Controller.set()), el componente se vuelve a renderizar y useFetch() devuelve automáticamente los datos desnormalizados actualizados.

nota
  1. Los fetches idénticos se deduplican automáticamente
React Native

Al usar React Navigation, useFetch() disparará los fetches al recibir el foco si los datos se consideran obsoletos.

Dependencias condicionales

Usar null como segundo argumento de cualquier hook de Data Client significa "no hacer nada".

// todo could be undefined if id is undefined
const todo = useFetch(TodoResource.get, id ? { id } : null);

Tipos​

function useFetch(
endpoint: ReadEndpoint,
...args: Parameters<typeof endpoint> | [null]
): (PromiseLike<any> & { resolved: boolean }) | undefined;

Ejemplos​

Comprobar el estado del fetch​

Usa promise.resolved para comprobar si los datos aún se están cargando:

import { useFetch } from '@data-client/react';
import { PostResource } from './resources/Post';

function MasterPost({ id }: { id: number }) {
const promise = useFetch(PostResource.get, { id });
if (!promise.resolved) {
// fetch is in-flight
}
// ...
}

Precarga en NextJS​

Para evitar las cascadas de fetch en NextJS, a veces puede que necesites añadir precargas a las rutas de nivel superior.

More Demos