TinyBase logoTinyBase

useProvideQueries

The useProvideQueries hook is used to add a Queries object by Id to a Provider component, but imperatively from a component within it.

useProvideQueries(
  queriesId: string,
  queries: Queries,
): void
TypeDescription
queriesIdstring

The Id of the Queries object to be registered with the Provider.

queriesQueries

The Queries object to be registered.

returnsvoid

This has no return value.

Normally you will register a Queries object by Id in a context by using the queriesById prop of the top-level Provider component. This hook, however, lets you dynamically add a new Queries object to the context, from within a component. This is useful for applications where the set of Queries objects is not known at the time of the first render of the root Provider.

A Queries object added to the Provider context in this way will be available to other components within the context (using the useQueries hook and so on). If you use the same Id as an existing Queries object registration, the new one will take priority over one provided by the queriesById prop.

Note that other components that consume a Queries object registered like this should defend against it being undefined at first. On the first render, the other component will likely not yet have completed the registration. In the example below, we use the null-safe useQueries('petQueries')? to do this.

Example

This example creates a Provider context. A child component registers a Queries object into it which is then consumable by a peer child component.

import React from 'react';
import {createRoot} from 'react-dom/client';
import {createQueries, createStore} from 'tinybase';
import {
  Provider,
  useCreateQueries,
  useCreateStore,
  useProvideQueries,
  useQueries,
} from 'tinybase/ui-react';

const App = () => (
  <Provider>
    <RegisterQueries />
    <ConsumeQueries />
  </Provider>
);
const RegisterQueries = () => {
  const store = useCreateStore(() =>
    createStore().setRow('pets', 'fido', {color: 'brown', legs: 4}),
  );
  const queries = useCreateQueries(store, (store) =>
    createQueries(store).setQueryDefinition(
      'brownLegs',
      'pets',
      ({select, where}) => {
        select('legs');
        where('color', 'brown');
      },
    ),
  );
  useProvideQueries('petQueries', queries);
  return null;
};
const ConsumeQueries = () => (
  <span>
    {JSON.stringify(useQueries('petQueries')?.getResultTable('brownLegs'))}
  </span>
);

const app = document.createElement('div');
const root = createRoot(app);
root.render(<App />);
console.log(app.innerHTML);
// -> '<span>{\"fido\":{\"legs\":4}}</span>'

Since

v5.3.0