@gdo-bzh/suspense-utils
v1.0.0-rc.5
Published
![version](https://img.shields.io/npm/v/@gdo-bzh/suspense-utils)
Downloads
2
Readme
suspense-utils
the package contains: createResource(): a method to create a resource. A resource is anything we could fetch and cache.
Install
yarn add @gdo-bzh/suspense-utils react
Usage
import React from 'react'
import styled from '@xstyled/styled-components'
import { createResource, Resource } from '@gdo-bzh/suspense-utils'
import { ErrorBoundary } from '@gdo-bzh/error-boundary'
import { CircleDots } from '@gdo-bzh/spinner'
type Post = {
userId: number
id: number
title: string
body: string
}
let resource: Resource<Post[]>
const fetchPosts = () =>
fetch(`https://jsonplaceholder.typicode.com/posts`).then(response => response.json())
const Layout = styled.div`
position: relative;
display: flex;
justify-content: center;
`
const PostsList = styled.ul`
list-style: none;
`
const Post: React.FC<Post> = ({ title, body }) => (
<li>
<h2>{title}</h2>
<div>{body}</div>
</li>
)
const Posts: React.FC = () => {
if (!resource) {
resource = createResource<Post[]>(fetchPosts)
}
return (
<PostsList>
{resource
.read()
.slice(0, 10)
.map(post => (
<Post {...post} />
))}
</PostsList>
)
}
export const Example: React.FC = () => {
return (
<Layout>
<ErrorBoundary Fallback={({ error }) => <div>{error.message}</div>}>
<Suspense fallback={<CircleDots size="30px" />}>
<Posts />
</Suspense>
</ErrorBoundary>
</Layout>
)
}
Types
type Resource<T> = {
read: () => T
}
type CreateResource<T> = (
asyncFunc: (extraData?: Data) => Promise<T>,
extraData?: Data
) => Resource<T>
License
MIT © gdo-bzh