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

@ryfylke-react/create-api-slice

v1.0.6

Published

Lets you create slices that handle loading state for async thunks automatically

Downloads

9

Readme

@ryfylke-react/create-api-slice

Adds automatic loading state to async thunks. Used as a drop-in replacement for @reduxjs/toolkit's createSlice.

Usage

yarn add @ryfylke-react/create-api-slice
# or
npm i @ryfylke-react/create-api-slice

Create the slice as you normally would, but make sure state is part of your schema. It should take a type of StateStatus. Use our createAPISlice function instead of createSlice from redux toolkit.

slices/postSlice.ts

import {
  createAPISlice,
  StateStatus,
} from "@ryfylke-react/create-api-slice";

const initialState = {
  ...baseInitialState,
  state: StateStatus.IDLE,
};

const postSlice = createAPISlice({
  name: "post",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(getPost.fulfilled, (state, { payload }) => {
        state.post = payload;
      })
      .addCase(getPost.rejected, (state) => {
        state.post = null;
      });
  },
});

export const postReducer = postSlice.reducer;

Then, when you create thunks that require loading state, make sure to append :load to the thunk name.

slices/postThunks.ts

export const getPost = createAsyncThunk(
  `post/getPost:load`,
  async (slug: string, { rejectWithValue }) => {
    return axios
      .get<PostData[]>(`${API_URL}/posts?slug=${slug}`)
      .then((res) => res.data[0])
      .catch((err) => rejectWithValue(err));
  }
);

Calling dispatch(getPost("...")) will now automatically set the loading state to 1 (PENDING), which will again automatically change to 2 (FULFILLED) or 3 (REJECTED).

Here's how you'd implement this logic on the UI:

// ...
import { StateStatus } from "@ryfylke-react/create-api-slice";

const App = () => {
    const { id } = useParams();
    const dispatch = useDispatch();
    const { state, post } = useSelector((state) => state.post);

    useEffect(() => {
        dispatch(getPost(id));
    }, []);

    if (state === StateStatus.REJECTED) {
        return "Error from server";
    }
    if (state === StateStatus.FULFILLED) {
        return (...);
    }
    return "Loading...";
}

This unfortunately only supports one concurring loading state per slice. This means that if you call two async thunks that both have :load appended - they will both mutate the same loading state.

Options

If you want, you can add a second parameter to createAPISlice, which is an options object of type APISliceOpts:

type APISliceOpts<T> = {
  /** The key that stores the StateStatus in the slice. Default `state`. */
  key?: string;
  /** The identifier used to add loading state. Default `:load` */
  identifier?: string;
  /** Replaces the createSlice function used internally */
  createSliceOverwrite?: (
    options: CreateSliceOptions<T, SliceCaseReducers<T>, string>
  ) => any;
};