Skip to content

Commit

Permalink
fix: MergedStore allows updating child component
Browse files Browse the repository at this point in the history
  • Loading branch information
adrian-marcelo-gallardo committed Feb 17, 2021
1 parent 170be29 commit 3c7f5a5
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 7 deletions.
21 changes: 15 additions & 6 deletions src/createMergedStore.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@ import React from "react";
import { mergedConnectContextFactory, useMergedConnectedContextFactory } from './connectContext';
import { getProviderContext } from './createContextProvider';

import { CustomProvider, ConnectContextFactory, KeyValue, ConnectContextOptions, ProviderCollection, ContextCollection } from "./typings";
import { CustomProvider, ConnectContextFactory, KeyValue, ConnectContextOptions, ProviderCollection, ContextCollection, OnInit } from "./typings";

type MergedStoreProps = {
children: React.ReactNode;
onInit?: OnInit;
}

const DefaultChild = ({ children }: any) => children;

Expand All @@ -24,20 +29,24 @@ function createMergedStore(providers: ProviderCollection): [CustomProvider, Conn
const withStore = mergedConnectContextFactory(contexts);
const useStore = useMergedConnectedContextFactory(contexts);

const MergedStore = (props: KeyValue) => {
const MergedStore = ({ children, onInit }: MergedStoreProps) => {

// onInit is supposed to be run only the first time, so we store a reference to its initial value and never update again
const [onInitFn] = React.useState(onInit);

// TODO: this needs to be connected or can just read the merged values from the context similar to createContextProvider onInit
const Child = props.onInit ? getConnectedChild(withStore, props.onInit) : DefaultChild;
const Child = React.useMemo(() => onInitFn ? getConnectedChild(withStore, onInitFn) : DefaultChild, []);

let wrapper: any = <Child {...props} />;
let wrapper: any = <Child children={children} />;

Object.values(providers).forEach((Provider) => {
const previousWrapper = wrapper;

wrapper = <Provider>{ previousWrapper }</Provider>
});

return React.useMemo(() => wrapper, []);
}
return wrapper;
};

return [
MergedStore,
Expand Down
4 changes: 3 additions & 1 deletion src/typings.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,6 @@ export type ConnectContextOptions = {
export type ConnectContextFactory = (Component: CustomComponent, options: ConnectContextOptions) => React.FunctionComponent;

export type ProviderCollection = CustomProvider[] | {[key: string]: CustomProvider}
export type ContextCollection = React.Context<any>[] | {[key: string]: React.Context<any>}
export type ContextCollection = React.Context<any>[] | {[key: string]: React.Context<any>}

export type OnInit = [ConnectContextOptions, (params: any) => void]

0 comments on commit 3c7f5a5

Please sign in to comment.