hook-hoc
TypeScript icon, indicating that this package has built-in type declarations

1.2.0 • Public • Published

Hook Higher Order Component (HOC)

CircleCI Coverage Status npm downloads gzip size npm version PRs Welcome

Use React hooks with your class components by Higher Order Component.

Warning:

This is intended to help incrementally transition large existing class components to hooks. Please write new components using functions!

Data fetching Example

Let's fetch some data using Reactive Data Client. We use the provided id prop to know what to fetch, then inject user and friends by returning an object with those props.

import withHook from 'hook-hoc';
import { useSuspense } from '@data-client/react';

import UserResource from 'resources/User';

const useProfile = ({ id }: { id: number }) => {
  const user = useSuspense(UserResource.get, { id });
  const friends = useSuspense(UserResource.getList, { id });
  return { user, friends };
};

class Profile extends React.PureComponent<{
  id: number;
  user: UserResource;
  friends: UserResource[];
}> {
  //...
}

export default withHook(useProfile)(Profile);

Forms Example

Here's an example of using a theoretical forms handling library

import React from 'react';
import withHook from 'hook-hoc';
import { useFields, FormValues } from '@cb/forms';

import SignupForm from './SignupForm';

// export this for testing if needed
export function useSignupFields() {
  const fields = useFields(SignupForm);
  const [submit] = useSubmitter(SignupForm);
  return { ...fields, submit };
}

type Props = FormValues<SignupForm> & {
  submit: (options?: object) => Promise<any>;
};

class SignupFields extends React.PureComponent<Props> {
  render() {
    const { submit, username, password } = this.props;

    return (
      <form
        onSubmit={e => {
          e.preventDefault();
          submit();
        }}
      >
        <InputField {...username} />
        <InputField {...password} type="password" />
        <button type="submit">SignUp</button>
      </form>
    );
  }
}
export default withHook(useSignupFields)(SignupFields);

Package Sidebar

Install

npm i hook-hoc

Weekly Downloads

190

Version

1.2.0

License

Apache-2.0

Unpacked Size

25.6 kB

Total Files

8

Last publish

Collaborators

  • ntucker