0.0.1 • Published 3 years ago

@ysuzuki19/use-promised v0.0.1

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

use-promised

react hooks library for handing promise without async or useEffect.

install

npm i @ysuzuki19/use-promised

how to use ( with jsonplaceholder )

import usePromised from '@ysuzuki19/use-promised';

interface Todo {
  userId: number;
  id: number;
  title: string;
  completed: boolean;
}

function App() {
  const { data, loading } = usePromised<Todo[]>(() =>
    fetch('https://jsonplaceholder.typicode.com/todos').then((response) =>
      response.json()
    )
  );

  if (loading || !data) {
    return <p>loading...</p>;
  }

  const todos = data;
  return (
    <>
      {todos.map((todo) => (
        <h3>
          {todo.completed ? '☑' : '☒'} {todo.title} ( id: {todo.id})
        </h3>
      ))}
    </>
  );
}

API

usePromised<T>(fn, deps, option);

fn is function to return promise. (it is callable)

deps is dependencies array (like useEffect).

option is option for handling promise. it has following key-val.

keytypemustval
placeholderTfalseinitial data
intervalnumberfalseinterval time (ms) for continuous refetch

status usage

nametype
dataTresult of promise
loadingbooleanis true while loading
errorbooleanis true if promise failed
successbooleanis true if promise succeed
refresh() => voidfunction for refreshing (without deps)