|
348 | 348 | * @since v4.1.0 |
349 | 349 | */ |
350 | 350 | /// useStoreOrStoreById |
| 351 | +/** |
| 352 | + * The useProvideStore hook is used to add a Store object by Id to a Provider |
| 353 | + * component, but imperatively from a component within it. |
| 354 | + * |
| 355 | + * Normally you will register a Store by Id in a context by using the |
| 356 | + * `storesById` prop of the top-level Provider component. This hook, however, |
| 357 | + * lets you dynamically add a new Store to the context, from within a descendent |
| 358 | + * component. This is useful for applications where the set of Stores is not |
| 359 | + * known at the time of the first render of the root Provider. |
| 360 | + * |
| 361 | + * A Store added to the Provider context in this way will be available to other |
| 362 | + * components within the context (using the useStore hook and so on). If you use |
| 363 | + * the same Id as an existing Store registration, the new one will take priority |
| 364 | + * over one provided by the `storesById` prop. |
| 365 | + * |
| 366 | + * Note that other components that consume a Store registered like this should |
| 367 | + * defend against it being undefined at first. On the first render, the other |
| 368 | + * component will likely not yet have completed the registration. In the example |
| 369 | + * below, we use the null-safe `useStore('petStore')?.getTableIds()` to do this. |
| 370 | + * @param storeId The Id of the Store object to be registered with the Provider. |
| 371 | + * @param store The Store object to be registered. |
| 372 | + * @example |
| 373 | + * This example creates a Provider context. A child component registers a Store |
| 374 | + * into it which is then consumable by a peer child component. |
| 375 | + * ```jsx |
| 376 | + * const App = () => ( |
| 377 | + * <Provider> |
| 378 | + * <RegisterStore /> |
| 379 | + * <ConsumeStore /> |
| 380 | + * </Provider> |
| 381 | + * ); |
| 382 | + * const RegisterStore = () => { |
| 383 | + * const store = useCreateStore(() => |
| 384 | + * createStore().setCell('pets', 'fido', 'color', 'brown'), |
| 385 | + * ); |
| 386 | + * useProvideStore('petStore', store); |
| 387 | + * return null; |
| 388 | + * }; |
| 389 | + * const ConsumeStore = () => ( |
| 390 | + * <span>{JSON.stringify(useStore('petStore')?.getTableIds())}</span> |
| 391 | + * ); |
| 392 | + * |
| 393 | + * const app = document.createElement('div'); |
| 394 | + * const root = ReactDOMClient.createRoot(app); |
| 395 | + * root.render(<App />); // !act |
| 396 | + * console.log(app.innerHTML); |
| 397 | + * // -> '<span>["pets"]</span>' |
| 398 | + * ``` |
| 399 | + * @category Store hooks |
| 400 | + * @since v4.4.2 |
| 401 | + */ |
| 402 | +/// useProvideStore |
351 | 403 | /** |
352 | 404 | * The useHasTables hook returns a boolean indicating whether any Table objects |
353 | 405 | * exist in the Store, and registers a listener so that any changes to that |
|
0 commit comments