Skip to content

steaks/leo-query

Repository files navigation

A simple library to connect async queries to Zustand stores.

Try a live demo here. And see full documentation here. And chat on discord here.

Installation

npm i leo-query

Getting Started

Hook up async queries in three steps:

  • Write async functions.
  • Connect your store.
  • Bind your components.
/**********************************************************
 * Write async functions                                  *
 **********************************************************/
const fetchDogs = (): Promise<number> => 
  fetch('https://good.dog.com/dogs').then(r => r.json());

const increasePopulation = (): Promise<void> =>
  fetch('https://good.dog.com/increasePopulation', {method: "POST"});

const removeAllDogs = (): Promise<void> =>
  fetch('https://good.dog.com/removeAllDogs', {method: "POST"});

/**********************************************************
 * Connect your store                                     *
 **********************************************************/

interface DogsState {
  dogs: Query<DogsState, number>;
  increasePopulation: Effect<DogsState, []>;
  removeAllDogs: Effect<DogsState, []>;
}

const useDogsStore = create(() => ({
  increasePopulation: effect(increasePopulation),
  removeAllDogs: effect(removeAllDogs),
  dogs: query(fetchDogs, s => [s.increasePopulation, s.removeAllDogs]) // Re-fetch when increasePopulation or removeAllDogs succeeds 
}));

const useDogStoreAsync = hook(useDogStore);

/**********************************************************
 * Bind your components                                   *
 **********************************************************/

const DogCounter = () => {
  const dogs = useDogStoreAsync(s => s.dogs);
  return <h1>{dogs} around here ...</h1>;
}

const Controls = () => {
  const increasePopulation = useDogStore(s => s.increasePopulation.trigger);
  return <button onClick={increasePopulation}>one up</button>;
}

const App = () => {
  return (
    <>
      {/* Leo Query works with Suspense */}
      <Suspense fallback={<h1>Loading...</h1>}>
        <DogCounter />
      </Suspense>
      <Controls />
    </>
  );
}

Why Leo?

Leo Query is simple, robust, and designed for Zustand. Read more about why Leo Query is different from other libraries in Why Leo Query?.

Examples

Example Description
Dogs JS A simple dog counter (Javascript)
Dogs TS A simple dog counter (Typescript)
Task Manager A more complex task manager app.