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

pinia-fetch-store

v1.0.2

Published

A small library for request state management when using Pinia.

Downloads

3

Readme

pinia-fetch-store

A small library for request state management when using Pinia. The purpose of the library is to eliminate boilerplate code when fetching data is involved in web applications that use Pinia library.

Installation

Using the ES Module Build

You can use any of your preferred package managers to install the library.

  npx install pinia-fetch-store

  yarn add pinia-fetch-store

Getting Started

Please find below an example of creating a todos Pinia fetch store.

export const useTodosStore = defineStore('todos', createFetchStore({
  endpoints: (builder) =>({
    create: builder.create<Todo,CreateTodo>({
      async requestFn(payload){
        const response = await axios.post<Todo>('/api/todos', payload)
        this.listAction();
        return response.data;
      }
    }),
    list: builder.create<Todo[], void>({
      async requestFn(){
        const response = await axios.get<{data: Todo[]}>('/api/todos');
        return response.data.data;
      }
    }),
    update: builder.create<Todo, UpdateTodo>({
      async requestFn(payload) {
        const {id, ...body} = payload;
        const response = await axios.put<Todo>(`/api/todos/${id}`, body);
        this.listAction();
        return response.data;
      }
    }),
    delete: builder.create<void, string>({
      async requestFn (id) {
        await axios.delete(`/api/todos/${id}`);
        this.listAction();
      }
    })
  })
}));

Then, we can start consuming the store from our Vue components.


const store = useTodosStore();

const listData = store.list.data 
const isListLoading = store.list.isLoading;

// You can also use the computed() method to make the state reactive
const isDeleteLoading = computed(() => store.delete.isLoading)

// For each endpoint the library creates a getter method (adding 'Computed' as suffix to the endpoint name)
store.listComputed.data
store.listComputed.isLoading

// For each endpoint the library creates an action method (adding 'Action' as suffix to the endpoint name)
store.listAction();

APIs

createFetchStore()

Th sole exported method which allows you to define a Pinia store

  • Syntax
createFetchStore<E extends Endpoints>({endpoints}: CreateFetchStoreOptions<E>): FetchStoreDefinition<E>
  • Parameters
    • endpoints: a callback function which must return an object literal with API endpoints. The callback function accepts EndpointBuilder object as parameter.

      Important Types

      • EndpointBuilder: an object with create() method that allows you to write your API endpoints.
        type EndpointBuilder  = {
          create<ResultType,RequestArg>(definition: EndpointDefinition<ResultType, RequestArg>): EndpointDefinition<ResultType, RequestArg>;
        }
      • Endpoints: an object literal that contains API endpoint definitions.
        type Endpoints = Record<string, EndpointDefinition<any, any>>;
      • EndpointDefinition: describes how an API endpoint retrieves the data from the server. The first generic parameter defines the result type which requestFn() must return whereas the second generic parameter defines the type of the parameter which requestFn() accepts (if it has any).
          export type EndpointDefinition<ResultType, RequestArg> = {
            requestFn(arg: RequestArg): MaybePromise<ResultType>;
          };
  • Return value
    • A Pinia store with the state, getters, and actions for each API endpoint.

      Important Types

      • FetchStoreDefinition: defines a Pinia store.
          type FetchStoreDefinition<E extends Endpoints> = {
            state: () => FetchStoreState<E>;
            getters: FetchStoreGetters<E>;
            actions: FetchStoreActions<E>;
          };
      • FetchStoreRequestState: defines the state of each API endpoint request.
        type FetchStoreRequestState<E extends EndpointDefinition<any, any>> = {
          isLoading: boolean;
          hasError: boolean;
          error: any | null;
          data: ResultTypeFrom<E> | null;
        };

Caveats

Please find below some of the quirky traits that come with the library implementation:

  • the library will ignore the request if a previous request has not finished loading.
  • the library is weakly typed with 'this' reference in requestFn() method implementation. It only expects a method whose suffix is 'Action' and it does not check if the action method actually is found in the store.

Feature Requests

  • create actions for each endpoint that clear the request state, e.g. clearListAction().
  • caching: build a mechanism to fetch data from server only when it becomes invalid.