Skip to content

Latest commit

 

History

History
82 lines (69 loc) · 1.82 KB

EXAMPLE.md

File metadata and controls

82 lines (69 loc) · 1.82 KB

Example

Step by step

- Define your context Code

export const APP_CONTEXT: React.Context<AppContext> = React.createContext(null);

export interface AppContext {
  personService: IPersonService;
}

- Define context value Code

export interface IPersonService {
  getName(personId: string): Promise<string>;
}

export function personService(): IPersonService {
  return {
    getName(id: string): Promise<string> {
      return Promise.resolve("A name") // fake implementation
    }
  }
}

- Export dependencies Code

export const appDependencies: AppContext = {
  personService: personService()
}

- Add context to your app Code

function App() {
    return <APP_CONTEXT.Provider value={appDependencies}>
        <PersonWrapperComponent/>
    </APP_CONTEXT.Provider>
}

- Create the component you want to connect Code

interface PersonComponentProps {
  personService: IPersonService;
  id: string;
}

function PersonComponent(props: PersonComponentProps) {
  const [name, setName] = React.useState("");

  const getName = async() => {
    const newName = await props.personService.getName(props.id);
    setName(newName);
  };

  return <>
    <button onClick={getName}>Load details</button>
    <p>{name}</p>
  </>
}

- Connect the component Code

function mapContextToProps(context: AppContext) {
  return {
    personService: context.personService
  }
}

export const PersonComponentHOC = connectContext(APP_CONTEXT)(PersonComponent, mapContextToProps);

- Use it Code

function PersonWrapperComponent() {
  return <PersonComponentHOC id='123'/>
}