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 🙏

© 2025 – Pkg Stats / Ryan Hefner

react-redux-request-controller

v1.0.3

Published

Данная библиотека берет на себя совершение запросов на бэк. Записывает в ```store``` состояние запросов, которые грузятся или провалились. Предоставляет хуки: ```useIsLoading``` и ```useIsError```. Предоставляет хук: ```useDataSelector```, который авто

Readme

react-redux-request-controller

Описание

Данная библиотека берет на себя совершение запросов на бэк. Записывает в store состояние запросов, которые грузятся или провалились. Предоставляет хуки: useIsLoading и useIsError. Предоставляет хук: useDataSelector, который автоматически берет данные.

Подключение

Чтобы подключить библиотеку, необходимо модифицировать ваш store:

  1. Подключить formControllerReducer
import {requestControllerReducer} from "react-redux-request-controller";

const combinedReducer = combineReducers({
  requestController: requestControllerReducer, // подключение requestControllerReducer
  user: userReducer,
  contact: contactReducer,
});
  1. Записать функцию getState в window
window.getState = () => store.getState()
  1. rootUrl берется из process.env.REACT_APP_SERVER_API_URL, поэтому, скрипт для запуска приложения, должен выглядеть как-то так:
   "start-develop": "PORT=3000 REACT_APP_SERVER_API_URL=http://11.111.111.1111:8000 react-scripts start",
  1. Авторизационный токен должен храниться в window.token

Документация

  1. requestController Полагаю, имеет смысл вставить интерфейс.
interface IRequestController {
  onSuccess?: (data: any) => void;
  onFailed?: (errors: any | undefined) => void;
  serialize?: (data: any) => void;

  method: "POST" | "GET" | "DELETE" | "PUT";
  id: string;
  action: any;
  url: string;
  params?: object;
}

onFailed - в случае, если запрос окончился ошибкой, вызовется без параметров. Если статус ответа - 400, вызовется с данными, которые пришли с бэка. serializer - необходим, если вы хотите поменять структуру данных, которые пришли с бэка. id - уникальный идентификатор запроса. Если запрос на удаление или на обновление, имеет смысл, id записывать как-то так: updateItem24, где 24 это id обновляемого компонента. 2) useIsLoading && useIsError Принимают всего 1 параметр: id запроса. 3) getIsLoading && getIsError Также принимают всего 1 параметр: id запроса. 4) useDataSelector Принимает 3 параметра: selector, isLoading(функция, которая возвращает boolean), getDefaultFunction(функция, для взятия данных, которая оборачивается в dispatch). ###Конечный код

import {RootState, store} from "../store";
import {useDataSelector} from "../../utils/phoenix/useData";
import {createContact, deleteContactData, getContactData, updateContactData} from "./thunks";
import {IUser} from "../user/model";
import {getIsError, getIsLoading, useIsError, useIsLoading} from "react-redux-request-controller";

export const Contact = {
  useData: () => useDataSelector(
    (state: RootState) => state.contact.contact,
    Contact.object.getIsLoading,
    getContactData
  ) as Array<IContact> | null,

  useIsLoading: () => useIsLoading('getContactData'),
  useIsError: () => useIsError('getContactData'),
  object: {
    getData: () => store.getState().contact.contact as Array<IContact> | null,
    getIsLoading: () => getIsLoading('getContactData'),
    getIsError: () => getIsError('getContactData'),
  },
  options: {
    create: (data:ICreateContact) => window.dispatch(createContact(data)),
    update: (data:IUpdateContact) => window.dispatch(updateContactData(data)),
    delete: (data:IDeleteContact) => window.dispatch(deleteContactData(data)),
  }
}

export interface IContact {
  id: string | number;
  phone: string;
  name: string;

  user?: IUser;
}

//****************** Options interface ******************//

export interface ICreateContact {
  phone: string;
  name: string;
}

export interface IUpdateContact {
  id?: string | number;
  phone: string;
  name: string;
}

export interface IDeleteContact {
  id: string | number;
}

Эта библиотека создана, чтобы создавать model.ts. В данном файле почти нет логики. Это лишь удобный интерфейс, с очень удобным синтаксисом, для взаимодействия с моделью Contact. Я считаю, что данный подход лучше, чем рандомно раскиданные экшены и селекторы. Да и код

const userData = User.useData()

Куда более чистый и лаконичный, чем

const userData = useSelector(userDataSelector)

или

User.options.login(data)

лучше, чем

const dispatch = useDispatch()
dispatch(userLogin(data))