TinyBase logoTinyBase

useStoreOrStoreById

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

useStoreOrStoreById(storeOrStoreId?: StoreOrStoreId): Store | undefined
TypeDescription
storeOrStoreId?StoreOrStoreId

Either an Id for accessing a Store object that was named with an Id in the Provider, or the Store object itself.

returnsStore | undefined

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

This is mostly of use when you are developing a component that needs a Store 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 Store-based components).

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

Example

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

import {Provider, useStoreOrStoreById} from 'tinybase/ui-react';
import React from 'react';
import {createRoot} from 'react-dom/client';
import {createStore} from 'tinybase';

const App = ({store}) => (
  <Provider store={store}>
    <Pane />
  </Provider>
);
const Pane = ({store}) => (
  <span>{JSON.stringify(useStoreOrStoreById(store).getTableIds())}</span>
);

const store = createStore().setCell('pets', 'fido', 'color', 'brown');
const app = document.createElement('div');
const root = createRoot(app);
root.render(<App store={store} />);
console.log(app.innerHTML);
// -> '<span>["pets"]</span>'

Since

v4.1.0