Context.Provider

A React component. Provides an observable to its descendants.

Definition

interface Provider extends Component<{
  children?: ReactNode
  onMount?(store: WrappedStateContainer): void
  onUnmount?(store: WrappedStateContainer): void
}, {}> {}

Props

children

Nothing special here. Just a normal React node or array of nodes. These children and their descendants will be able to consume the provided observable.

onMount

Optional. This is a function that will be called in the Provider's componentDidMount lifecycle hook after the provider subscribes to the Context's observable.

Definition

(store: WrappedStateContainer) => void

store – the provided observable. See the WrappedStateContainer type

onUnmount

Optional. This is a function that will be called in the Provider's componentWillUnmount lifecycle hook.

Definition

(store: WrappedStateContainer) => void

store – the provided observable. See the WrappedStateContainer type

Example

The onMount and onUnmount hooks are useful for attaching/detaching a child store to/from a parent store.

import React from 'react'
import { StoreApi, createContext } from 'react-zedux'
import { createStore } from 'zedux'

class CounterApi extends StoreApi {
  static idCounter = 0

  id = CounterApi.idCounter++
  store = createStore().hydrate(0)
}

const rootStore = createStore()
const CounterContext = createContext(CounterApi)

const Counter = () => (
  <CounterContext.Injector
    onMount={counterStore => {

      // Attach to the root store when the component mounts
      rootStore.use({
        [counterStore.id]: counterStore
      })
    }}
    onUnmount={counterStore => {

      // Unattach this store when the component unmounts
      rootStore.use({
        [counterStore.id]: null
      })
    }}
  >
    {counterStore => JSON.stringify(rootStore.state)}
  </CounterContext.Injector>
)

results matching ""

    No results matching ""