0.4.1 • Published 3 years ago

simple-cell v0.4.1

Weekly downloads
-
License
-
Repository
github
Last release
3 years ago

Simple Cell

A React package to simplify the rendering logic of your components. Inspired by RedwoodJS Cells and react-cell. Unlike those libraries, simple-cell doesn't include any data fetching logic.

Install

npm i simple-cell
# or
yarn add simple-cell

Before

const Animals = () => {
  const { data, loading, error } = useQuery(getAnimalsQuery)

  if (loading) return <>Loading...</>
  if (error) return <>Something went wrong</>
  if (!data?.getAnimals) return <>No animals here</>

  return data?.getAnimals.map(a => <div key={a.id}>{a.name}</div>)
}

After

import { makeCell } from 'simple-cell'

const AnimalsCell = makeCell({
  Success: ({ data: animals }) => animals.map(a => <div key={a.id}>{a.name}</div>),
  Loading: () => <>Loading...</>,
  Failure: ({ error }) => <>Something went wrong: {error.message}</>,
  Empty: () => <>No animals here</>,
})

const Animals = () => {
  const { data, loading, error } = useQuery(getAnimalsQuery)

  return <AnimalsCell data={data?.getAnimals} loading={loading} error={error} />
}

Note that if data is an array, the Empty component will be shown if its length is 0.

Extra Props

Props are passed along to all the components, so you can do:

const Cell = makeCell({
  Success: ({ whatever }) => <>{whatever}</>,
})

// ...

<Cell whatever={'whatever'} />

Deferred Loading

By default, the loading component is deferred by 300ms. This is a technique to make the UI feel more reactive by not showing a loading state if the loading is fast enough to "feel instantaneous". You can disable or customize that duration with the loadingDelay prop.

<Cell loadingDelay={0} />

If you want to use simple-cell's deferred mechanism outside of makeCell, you can import directly the useDeferredLoading hook or the DeferredLoading component:

import { useDeferredLoading, DeferredLoading } from 'simple-cell'

const LoadingWithHook = () => {
  const show = useDeferredLoading(200)
  return show ? <>Loading...</> : null
}

const LoadingWithComponent = () => <DeferredLoading delay={200}>Loading...</DeferredLoading>

Conditional rendering

You may want to render only if some condition is met. Use the renderIf prop to do so:

<Cell renderIf={isSomethingReady} />
0.4.1

3 years ago

0.4.0

3 years ago

0.3.0

3 years ago

0.2.0

3 years ago

0.1.0

3 years ago