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?: QueriesOrQueriesId): Queries | undefined
Type | Description | |
---|---|---|
queriesOrQueriesId? | QueriesOrQueriesId | Either an |
returns | Queries | undefined | A reference to the |
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.
import React from 'react';
import {createRoot} from 'react-dom/client';
import {createQueries, createStore} from 'tinybase';
import {Provider, useQueriesOrQueriesById} from 'tinybase/ui-react';
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 = createRoot(app);
root.render(<App queries={queries} />);
console.log(app.innerHTML);
// -> '<span>["dogColors"]</span>'
Since
v4.1.0