Ernest Trachuk
Ernest Trachuk

Reputation: 11

how to use functional mobX store in react class components?

here is my init store function:

import React, { FC } from 'react';
import { useLocalObservable } from 'mobx-react';

import { TestStore, ITestStore } from './TestStore';

interface IStoreContext {
    testStore: ITestStore;
}

export const StoreContext = React.createContext<IStoreContext>({} as IStoreContext);

export const StoreProvider: FC = ({ children }) => {
    const testStore = useLocalObservable(TestStore);

    const stores = {
        testStore,
    };

    return <StoreContext.Provider value={stores}>{children}</StoreContext.Provider>;
};

export const useRootStore = () => {
    const rootStore = React.useContext(StoreContext);

    if (!rootStore) {
        throw new Error('useStore must be used within a StoreProvider');
    }

    return rootStore;
};

and this is how i use it:

const { testStore } = useRootStore();

But I can't use the hook inside the class component. So how get the store inside the class component ? thanks.

Upvotes: 1

Views: 1425

Answers (1)

Tholle
Tholle

Reputation: 112917

You can create a Higher-Order Component that uses your hook and passes the result to the wrapped class component.

Example

function withRootStore(Component) {
  return function WrappedComponent(props) {
    const rootStore = useRootStore();

    return <Component {...props} rootStore={rootStore} />;
  }
}

// ...

class MyComponent extends React.Component {
  render() {
    const { testStore } = this.props.rootStore;

    // ...
  }
}

export default withRootStore(MyComponent);

Upvotes: 1

Related Questions