0.2.0 • Published 5 years ago

react-with-lazy v0.2.0

Weekly downloads
3
License
MIT
Repository
github
Last release
5 years ago

react-with-lazy

Package to easily launch react hooks' suspense with Promise.
Cache results in Promsie definition units.
The result is done at the same time as the destruction of the component. Also, it is possible to cache permanently.

Installation

$ npm install react-with-lazy # or yarn add react-with-lazy

Usage

import withLazy, { LazyComponentProps } from 'react-with-lazy'

const Employees = ({ useLazy }: LazyComponentProps) => {
  const { state: { page, rowsPerPage } } = useContext(PaginationContext)
  const employees = useLazy<Employee[]>(
    () => api.get('employees', { page, rowsPerPage }).then(res => res.json()),
    [page, rowsPerPage]
  )

  return (
    <React.Fragment>
      {employees.map((employee, key) => (
        <ul key={key}>
          <li>{employee.id}</li>
          <li>{employee.employee_name}</li>
          <li>{employee.employee_salary}</li>
          <li>{employee.employee_age}</li>
          <li>{employee.profile_image}</li>
        </ul>
      ))}
    </React.Fragment>
  )
}

const LazyEmployees = withLazy(Employees)

export default () => (
  <React.Suspense fallback={<Loading />}>
    <LazyEmployees />
  </React.Suspense>
)

or

import { createUseLazy } from 'react-with-lazy'

// Cache forever
const { useLazy } = createUseLazy({
  perpetual: true
})

const Employee = ({ id }: Props) => {
  const employee = useLazy<Employee>(
    () => api.get('employee', { id }).then(res => res.json()),
    [id]
  )

  return (
    <ul>
      <li>{employee.id}</li>
      <li>{employee.employee_name}</li>
      <li>{employee.employee_salary}</li>
      <li>{employee.employee_age}</li>
      <li>{employee.profile_image}</li>
    </ul>
  )
}

export default () => (
  <React.Suspense fallback={<Loading />}>
    <Employee />
  </React.Suspense>
)

API

useLazy can specify a promise and an array as an argument

useLazy<T = any, I = any>(
  promise: Promise<T> | (() => Promise<T>),
  inits?: I
): T

withLazy can be used by specifying Component

withLazy<P extends LazyComponentProps>(
  Component: ComponentType<P>,
  options?: CreateUseLazyOptions
): ReactElement

interfaces

CreateUseLazyOptions

{
  perpetual?: boolean
}

Other

When making it, I made reference to this source.
Thank you.

0.2.0

5 years ago

0.1.8

5 years ago

0.1.7

5 years ago

0.1.6

5 years ago

0.1.5

5 years ago

0.1.4

5 years ago

0.1.3

5 years ago

0.1.2

5 years ago

0.1.1

5 years ago

0.1.0

5 years ago