Fragno
Client frameworks

React

Learn how to integrate Fragno fragments into your React frontend

Edit on GitHub

React support is included in the @fragno-dev/core package.

To start, create a client instance and call the React useFragno function.

lib/example-fragment-client.ts
import { createExampleFragmentClient } from "@fragno-dev/example-fragment";
import { useFragno } from "@fragno-dev/core/react";

const exampleFragmentClient = createExampleFragmentClient();
export const exampleFragment = useFragno(exampleFragmentClient);

Basic Usage

In this example, we're using the useData hook to read from a GET route defined in the example-fragment library. An object can be passed to the hook to specify the path and query parameters. When these parameters change, the hook will automatically be re-fetched.

components/ExampleComponent.tsx
import { exampleFragment } from "@/lib/example-fragment-client";

export default function ExampleComponent() {
  const { data, loading, error } = exampleFragment.useData();

  return (
    <div>
      <h1>Example Component</h1>
      {loading ? <div>Loading...</div> : <div>{data}</div>}
      {error && <div>Error: {error.message}</div>}
    </div>
  );
}

Mutations

components/TodoComponent.tsx
import { exampleFragment } from "@/lib/example-fragment-client";

export default function TodoComponent() {
  const { useTodos, useAddTodo } = exampleFragment;
  const { data: todos, loading: todosLoading, error, refetch } = useTodos();
  const { mutate: addTodo, loading: addTodoLoading } = useAddTodo();

  if (todosLoading) {
    return <div>Loading...</div>;
  }

  if (error) {
    return <div>Error: {error.message}</div>;
  }

  return (
    <div>
      <h1>Todos</h1>
      {todos?.map(todo => (
        <div key={todo.id}>
          {todo.text} - {todo.done ? 'Done' : 'Pending'}
        </div>
      ))}

      <button
        onClick={() => addTodo({ body: { text: "New todo" } })}
        disabled={addTodoLoading}
      >
        {addTodoLoading ? "Adding..." : "Add Todo"}
      </button>

      <button onClick={() => refetch()}>Refresh</button>
    </div>
  );
}