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 🙏

© 2026 – Pkg Stats / Ryan Hefner

generate-api-slice-thunk

v1.0.5

Published

A utility to generate Redux Toolkit slices and async thunks for API requests.

Readme

generate-api-slice-thunk

A utility library that generates Redux Toolkit slices and async thunks for API requests in React Native apps with minimal boilerplate.

npm version license

Features

  • Automatically generates Redux Toolkit slices for your API requests
  • Creates async thunks with proper loading, success, and error states
  • Provides built-in actions to reset or update state directly
  • Supports token-based authentication
  • Handles multipart form data requests
  • Optimized for React Native applications
  • Customizable API request handling

Installation

npm install generate-api-slice-thunk

or

yarn add generate-api-slice-thunk

Quick Start

Here's a simple example of how to use generate-api-slice-thunk in a React Native project:

import generateApiSliceAndThunk from "generate-api-slice-thunk";

// Create a slice and thunk for login API
const { slice: loginSlice, request: loginThunk } = generateApiSliceAndThunk(
  "loginSlice",
  {
    endPoint: "/login",
    method: "post",
    tokenRequired: false,
    isMultiPart: false,
  },
  async (params, options) => {
    const { endPoint, method, tokenRequired, isMultiPart } = options;
    const baseUrl = "https://api.example.com";

    const response = await fetch(baseUrl + endPoint, {
      method,
      headers: {
        "Content-Type": isMultiPart
          ? "multipart/form-data"
          : "application/json",
        ...(tokenRequired && { Authorization: `Bearer ${yourTokenHere}` }),
      },
      body: isMultiPart ? params : JSON.stringify(params),
    });

    return response.json();
  }
);

// Export the slice and thunk for use in your app
export { loginSlice, loginThunk };

Setup Guide

Step 1: Project Structure

Create an organized structure for your API services in your React Native project:

src/
└── Networking/
    └── User/
        └── userServices.js

Step 2: Create Service File

In your userServices.js file:

import generateApiSliceAndThunk from "generate-api-slice-thunk";

// Login API
const { slice: loginSlice, request: loginThunk } = generateApiSliceAndThunk(
  "loginSlice",
  {
    endPoint: "/login",
    method: "post",
    tokenRequired: false,
    isMultiPart: false,
  },
  async (params, options) => {
    const { endPoint, method, tokenRequired, isMultiPart } = options;
    const baseUrl = "https://api.example.com";

    const response = await fetch(baseUrl + endPoint, {
      method,
      headers: {
        "Content-Type": isMultiPart
          ? "multipart/form-data"
          : "application/json",
        ...(tokenRequired && { Authorization: `Bearer ${yourTokenHere}` }),
      },
      body: isMultiPart ? params : JSON.stringify(params),
    });

    return response.json();
  }
);

export { loginSlice, loginThunk };

Step 3: Configure Redux Store

import { configureStore, combineReducers } from "@reduxjs/toolkit";
import { persistStore, persistReducer } from "redux-persist";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { loginSlice } from "./Networking/User/userServices";

const persistConfig = {
  key: "root",
  storage: AsyncStorage,
  whitelist: ["loginSlice"], // Only persist login data
};

const rootReducer = combineReducers({
  loginSlice: loginSlice.reducer,
  // Add other reducers here
});

const persistedReducer = persistReducer(persistConfig, rootReducer);

export const store = configureStore({
  reducer: persistedReducer,
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: false,
    }),
});

export const persistor = persistStore(store);

Step 4: Using the API in Components

import React, { useState } from "react";
import { View, Text, TextInput, Button } from "react-native";
import { useDispatch, useSelector } from "react-redux";
import { loginThunk, loginSlice } from "../Networking/User/userServices";

const LoginScreen = () => {
  const dispatch = useDispatch();
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");

  // Get data from store
  const userData = useSelector((state) => state.loginSlice.data);

  const handleLogin = async () => {
    try {
      const response = await dispatch(
        loginThunk({
          username,
          password,
        })
      ).unwrap();

      console.log("Login successful:", response);
      // Navigate or perform actions on success
    } catch (error) {
      console.error("Login failed:", error);
      // Handle error
    }
  };

  const handleLogout = () => {
    // Reset the state to null
    dispatch(loginSlice.actions.reset());
  };

  return (
    <View style={{ padding: 20 }}>
      {userData ? (
        <>
          <Text>Welcome, {userData.name}!</Text>
          <Button title="Logout" onPress={handleLogout} />
        </>
      ) : (
        <>
          <TextInput
            value={username}
            onChangeText={setUsername}
            placeholder="Username"
            style={{ borderWidth: 1, padding: 10, marginBottom: 10 }}
          />
          <TextInput
            value={password}
            onChangeText={setPassword}
            placeholder="Password"
            secureTextEntry
            style={{ borderWidth: 1, padding: 10, marginBottom: 20 }}
          />
          <Button title="Login" onPress={handleLogin} />
        </>
      )}
    </View>
  );
};

export default LoginScreen;

API Reference

generateApiSliceAndThunk(sliceName, options, apiCallback)

Creates a Redux Toolkit slice and async thunk for an API endpoint.

Parameters:

  • sliceName (string): Name of the slice
  • options (object): Configuration for API
    • endPoint (string): API endpoint (e.g., '/login')
    • method (string): HTTP method ('get', 'post', 'put', 'delete')
    • tokenRequired (boolean): Whether authentication token is required
    • isMultiPart (boolean): Whether to use multipart/form-data
  • apiCallback (function): Custom function to handle API requests

Returns:

  • slice: Redux Toolkit slice with reducer and actions
    • slice.actions.reset(): Action to reset state data to null
    • slice.actions.update(newData): Action to directly update state data
  • request: Async thunk function for API requests

State Structure

Each generated slice will have the following state structure:

{
  data: null; // API response data or manually updated data
}

Built-in Actions

The generated slice includes these built-in actions:

reset

Resets the state data to null. Useful for logout or clearing data.

dispatch(yourSlice.actions.reset());

update

Directly updates the state data with new values. Useful for local updates without API calls.

dispatch(yourSlice.actions.update(newData));

Examples

Image Upload with Multipart Form Data

const { slice: uploadSlice, request: uploadThunk } = generateApiSliceAndThunk(
  "uploadSlice",
  {
    endPoint: "/upload",
    method: "post",
    tokenRequired: true,
    isMultiPart: true,
  },
  async (formData, options) => {
    const { endPoint } = options;
    const baseUrl = "https://api.example.com";

    // For React Native, you'll need to properly format your FormData
    const formDataObj = new FormData();
    formDataObj.append("image", {
      uri: formData.uri,
      type: formData.type,
      name: formData.fileName,
    });

    const response = await fetch(baseUrl + endPoint, {
      method: "POST",
      headers: {
        "Content-Type": "multipart/form-data",
        Authorization: `Bearer ${yourTokenHere}`,
      },
      body: formDataObj,
    });

    return response.json();
  }
);

// In your component:
const handleImageUpload = async (imageUri) => {
  const imageData = {
    uri: imageUri,
    type: "image/jpeg",
    fileName: "photo.jpg",
  };

  dispatch(uploadThunk(imageData));
};

Handling User Profile

// Get user profile
dispatch(getUserThunk()).then((response) => {
  console.log("User profile:", response.payload);
});

// Update user profile locally before API sync
dispatch(
  userSlice.actions.update({
    ...currentUserData,
    name: "New Name",
    avatar: "new-avatar-url.jpg",
  })
);

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Contact

For questions or support, please contact: [email protected]