Frameworks
React

React

If you are using React, you can use the hooks provided by @triplit/react:

npm i @triplit/react

useQuery

The useQuery hook subscribes to the provided query inside your react component will automatically unsubscribe from the query when the component unmounts.

The result of the hook is an object with the following properties:

  • results: A Map containing the results of the query, with entity ids as keys and entities as values.
  • fetching: A boolean indicating whether the query is currently fetching.
  • error: An error object if the query failed to fetch.
import { useQuery } from '@triplit/react';
 
const client = new TriplitClient();
const query = client.query('todos');
 
function App() {
  const { results, fetching, error } = useQuery(client, query);
 
  if (fetching) return <div>Loading...</div>;
  if (error) return <div>Could not load data.</div>;
 
  return (
    <div>
      {results.entries().forEach((item) => (
        <div>{item.text}</div>
      ))}
    </div>
  );
}

useEntity

The useEntity hook subscribes to the provided entity inside your react component and will automatically unsubscribe from updates to the entity when the component unmounts.

The result of the hook is the same as the result of useQuery, but the results property will only contain the entity you subscribed to.

import { useEntity } from '@triplit/react';
 
const client = new TriplitClient();
 
function App() {
  const { results: entity } = useEntity(client, 'todos', '1');
 
  return <div>{entity.text}</div>;
}

useConnectionStatus

The useConnectionStatus hook subscribes to changes to the connection status of the client and will automatically unsubscribe when the component unmounts.

import { useConnectionStatus } from '@triplit/react';
 
const client = new TriplitClient();
 
function App() {
  const connectionStatus = useConnectionStatus(client);
 
  return (
    <div>
      The client is {connectionStatus === 'OPEN' ? 'connected' : 'disconnected'}
    </div>
  );
}