TinyBase logoTinyBase

useQueriesOrQueriesById

The useQueriesOrQueriesById hook is used to get a reference to a Queries object from within a Provider component context, or have it passed directly to this hook.

useQueriesOrQueriesById(queriesOrQueriesId?: any): Queries | undefined
TypeDescription
queriesOrQueriesId?any
returnsQueries | undefined

A reference to the Queries object (or undefined if not within a Provider context, or if the requested Queries object does not exist).

This is mostly of use when you are developing a component that needs a Queries object and which might have been passed in explicitly to the component or is to be picked up from the context by Id (a common pattern for Queries-based components).

This is unlikely to be used often. For most situations, you will want to use the useQueries hook.

Example

This example creates a Provider context into which a default Queries object is provided. A component within it then uses the useQueriesOrQueriesById hook to get a reference to the Queries object again, without the need to have it passed as a prop. Note however, that unlike the useQueries hook example, this component would also work if you were to pass the Queries object directly into it, making it more portable.

const App = ({queries}) => (
  <Provider queries={queries}>
    <Pane />
  </Provider>
);
const Pane = ({queries}) => (
  <span>
    {JSON.stringify(useQueriesOrQueriesById(queries).getQueryIds())}
  </span>
);

const queries = createQueries(
  createStore().setTable('pets', {
    fido: {species: 'dog', color: 'brown'},
    felix: {species: 'cat', color: 'black'},
    cujo: {species: 'dog', color: 'black'},
  }),
).setQueryDefinition('dogColors', 'pets', ({select, where}) => {
  select('color');
  where('species', 'dog');
});

const app = document.createElement('div');
const root = ReactDOMClient.createRoot(app);
root.render(<App queries={queries} />);
console.log(app.innerHTML);
// -> '<span>["dogColors"]</span>'

Since

v4.1.0