npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-extra-hooks

v2.3.4

Published

Hooks for data fetching and more

Downloads

208

Readme

react-extra-hooks

yarn add react-extra-hooks

hooks

  • usePromise
  • useLazyPromise
  • useDebounce
  • useLocalStorage

Examples

usePromise

import { usePromise } from 'react-extra-hooks'
import React from 'react'

const sleep = (t) => new Promise((res) => setTimeout(res, t))

async function pp() {
    await sleep(400)
    return {
        x: 9,
    }
}

const App = () => {
    const { result, loading, error } = usePromise(pp)
    if (loading) {
        return <>loading</>
    }
    return <div>{result?.x}</div>
}

useLazyPromise

import { useLazyPromise } from 'react-extra-hooks'
import React from 'react'

const sleep = (t) => new Promise((res) => setTimeout(res, t))

async function effect() {
    await sleep(400)
    alert('executed')
    return {
        x: 9,
    }
}

const UseLazyPromiseExample = () => {
    const [execute, { result, loading, error }] = useLazyPromise(pp)
    if (loading) {
        return <>loading</>
    }
    if (result) {
        return <div>{result?.x}</div>
    }
    return (
        <div>
            <button onClick={execute}>execute promise</button>
        </div>
    )
}

useLazyPromise with in memory cache, supports the options {promiseId: string, cacheSize: numer, cacheExpirationSeconds: number}. Every useLazyPromise cached the result based on

  • the argument passed to the execute function
  • the promiseId option (defaults to the name of the promise)

The cache is invalidated when

  • the page is refreshed
  • the cacheExpirationSeconds (defaults to 120 secods) times out
  • the cache overflows his size (that defaults to 50 elements), the first cached value is discarded
import { useLazyPromise } from 'react-extra-hooks'
import React from 'react'

const sleep = (t) => new Promise((res) => setTimeout(res, t))

async function effect(n: string) {
    await sleep(1000)
    // throw Error('xxx')
    alert('executed with n=' + n)
    return {
        x: n,
    }
}

const UseLazyPromiseExample = () => {
    const [arg, set] = useState('')
    const [execute, { result, loading, error }] = useLazyPromise(effect, {
        cache: true,
        cacheExpirationSeconds: 300,
    })
    if (loading) {
        return <>loading</>
    }
    if (error) {
        return <div>{error.message}</div>
    }

    return (
        <div>
            <input onChange={(e) => set(e.target.value)} value={arg} />
            <button onClick={() => execute(arg)}>execute promise</button>
            <code>
                <div>{result?.x}</div>
            </code>
        </div>
    )
}

Example with delayed argument necessary for the promise

const { query } = useRouter() // null on first render
const { result, loading, error } = usePromise(query ? asyncFunction : null, {
    cache: true,
    args: [query],
})

Usage with pagination

import { useLazyPromise } from 'react-extra-hooks'
import React from 'react'

const sleep = (t) => new Promise((res) => setTimeout(res, t))

const PaginationExample = () => {
    const [page, setPage] = useState(0)

    async function loadData(page) {
        const items = await fetchSomething({ page })
        return [...result, ...items]
    }

    const { result = [], loading, error } = usePromise(loadData, {
        args: [page],
    })

    if (!result.length) {
        return <>loading</>
    }

    if (error) {
        return <div>{error.message}</div>
    }

    return (
        <div>
            <span>page: {page}</span>
            <code>
                <div>
                    {result.map((x) => (
                        <div>{x}</div>
                    ))}
                    <button
                        disabled={loading}
                        onClick={() => setPage((x) => x + 1)}
                    >
                        {loading ? 'loading' : 'more'}
                    </button>
                </div>
            </code>
        </div>
    )
}

async function fetchSomething({ page }) {
    await sleep(1000)
    return Array(10)
        .fill(page + 10)
        .map((x, i) => x + i)
        .map((x) => x.toString())
}

Pagination with cursor

const ItemsList = ({}) => {
    const [after, setAfter] = useState(undefined)

    const getUserItems = useCallback(
        async (after): Promise<GetUserItemsQuery['Items']> => {
            const uid = getUid()
            const res = await sdk.GetUserItems({
                first: 3,
                after: after,
            })
            const newItems = res?.Items || ({} as any)
            return {
                ...newItems,
                nodes: [...(Items?.nodes || []), ...(newItems?.nodes || [])],
            }
        },
        [after],
    )

    const { result: Items, loading, error } = usePromise(getUserItems, {
        cache: true,
        args: [after],
    })

    const hasItems = !loading && Items?.nodes?.length

    if (!Items && loading) {
        return (
            <Center>
                <Spinner />
            </Center>
        )
    }
    if (error) {
        return (
            <Center>
                <ErrorMessage msg={error?.message} />
            </Center>
        )
    }
    if (!hasItems) {
        return (
            <Col align='center' justify='center' opacity={0.8} h='100%'>
                <NextLink href='/new'>
                    <Button>Create your first Item</Button>
                </NextLink>
            </Col>
        )
    }
    return (
        <Stack spacing={6}>
            {Items?.nodes?.map((item, i) => (
                <ItemCard key={i} data={item} />
            ))}
            {hasItems && Items?.pageInfo?.hasNextPage && (
                <Button
                    isLoading={loading}
                    isDisabled={loading}
                    onClick={(e) => setAfter(Items?.pageInfo?.endCursor)}
                >
                    Load More
                </Button>
            )}
        </Stack>
    )
}

TODO add support for suspense