New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

pullstate

Package Overview
Dependencies
Maintainers
1
Versions
99
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

pullstate - npm Package Compare versions

Comparing version 1.11.0 to 1.11.1

dist/batched.d.ts

13

Changelog.md

@@ -1,6 +0,6 @@

### 1.11.0
## 1.11.0
Added `AsyncActionName.use(args, options)` - a new way to make use of your Async Actions. By default it acts just like `useBeckon()`, except it returns an object instead of an array.
The object now includes more helpful flags, and is shaped like so:
This returned object now includes more helpful flags, and is shaped like so:

@@ -13,8 +13,7 @@ ```ts

isStarted: boolean;
error: boolean;
endTags: string[];
renderPayload: ((payload) => any) => any;
message: string;
raw: TPullstateAsyncWatchResponse<R, T>;
payload: R;
error: boolean;
renderPayload: ((payload: R) => any) => any;
}

@@ -25,6 +24,4 @@ ```

`raw` is the same as you would expect to receive from `useWatch()`. The first array property will be `true` if you have not set `initiate: false`, since that represents if this action has been started - and this method acts like `useBeckon()` by default.
`renderPayload` is a very useful function. You can use this in your React component to conditionally render stuff only when your action payload has returned successfully. You can use it like so:
`renderPayload` is a very useful function. You can use this in your React tree to conditionally render stuff only when your action payload has returned successfully. You can use it like so:
```typescript jsx

@@ -31,0 +28,0 @@ const userAction = LoadUserAction.use({ id: userId });

import { useStoreState } from "./useStoreState";
import { useStoreStateOpt } from "./useStoreStateOpt";
import { Store, TUpdateFunction, update } from "./Store";
import { Store, TUpdateFunction, update, TStoreAction } from "./Store";
import { InjectStoreState } from "./InjectStoreState";
import { createPullstateCore, IPullstateAllStores, IPullstateInstanceConsumable, PullstateContext, PullstateProvider, useInstance, useStores } from "./PullstateCore";
import { createPullstateCore, IPullstateAllStores, IPullstateInstanceConsumable, PullstateContext, PullstateProvider, TMultiStoreAction, useInstance, useStores } from "./PullstateCore";
import { createAsyncAction, errorResult, successResult } from "./async";

@@ -11,2 +11,2 @@ import { EAsyncActionInjectType, InjectAsyncAction, TInjectAsyncActionProps } from "./InjectAsyncAction";

export * from "./async-types";
export { useStoreState, useStoreStateOpt, update, Store, InjectStoreState, InjectStoreStateOpt, PullstateProvider, useStores, useInstance, createPullstateCore, createAsyncAction, successResult, errorResult, IPullstateInstanceConsumable, IPullstateAllStores, InjectAsyncAction, EAsyncActionInjectType, TInjectAsyncActionProps, TUpdateFunction, PullstateContext, TUseResponse, };
export { useStoreState, useStoreStateOpt, update, Store, InjectStoreState, InjectStoreStateOpt, PullstateProvider, useStores, useInstance, createPullstateCore, createAsyncAction, successResult, errorResult, IPullstateInstanceConsumable, IPullstateAllStores, InjectAsyncAction, EAsyncActionInjectType, TInjectAsyncActionProps, TUpdateFunction, TStoreAction, TMultiStoreAction, PullstateContext, TUseResponse, };

@@ -105,3 +105,3 @@ import isEqual from'fast-deep-equal/es6';import React,{useRef,useState,useEffect,useContext,useMemo}from'react';import produce$1,{produceWithPatches,produce,applyPatches}from'immer';function useStoreState(store, getSubState, deps) {

store._patchListeners.forEach(listener => listener(patches, inversePatches));
return getChangedPathsFromPatches(patches);
return Object.keys(getChangedPathsFromPatches(patches));
}

@@ -162,2 +162,3 @@ }

this.currentState = nextState;
this.batchState = undefined;
for (const runReaction of this.reactions) {

@@ -244,4 +245,11 @@ updateKeyedPaths.push(...runReaction());

}
createPathReaction(path, reaction) {
}
getRawState() {
return this.currentState;
if (this.batchState !== undefined) {
return this.batchState;
}
else {
return this.currentState;
}
}

@@ -251,2 +259,30 @@ useState(getSubState, deps) {

}
act(action) {
action((u, p) => this.batch(u, p));
this.flushBatch(true);
}
batch(updater, patchesCallback) {
if (this.batchState === undefined) {
this.batchState = this.currentState;
}
const func = typeof updater === "function";
const [nextState, patches, inversePatches] = runUpdates(this.batchState, updater, func);
if (patches.length > 0 && (this._patchListeners.length > 0 || patchesCallback)) {
if (patchesCallback) {
patchesCallback(patches, inversePatches);
}
this._patchListeners.forEach(listener => listener(patches, inversePatches));
}
this.batchState = nextState;
}
flushBatch(ignoreError = false) {
if (this.batchState !== undefined) {
if (this.batchState !== this.currentState) {
this._updateState(this.batchState);
}
}
else if (!ignoreError) {
console.error(`Pullstate: Trying to flush batch state which was never created or updated on`);
}
}
update(updater, patchesCallback) {

@@ -263,7 +299,6 @@ update(this, updater, patchesCallback);

if (nextState !== currentState) {
store._updateState(nextState, getChangedPathsFromPatches(patches));
store._updateState(nextState, Object.keys(getChangedPathsFromPatches(patches)));
}
}
function getChangedPathsFromPatches(changePatches) {
const updateKeyedPathsMap = {};
function getChangedPathsFromPatches(changePatches, prev = {}) {
for (const patch of changePatches) {

@@ -278,6 +313,6 @@ let curKey;

}
updateKeyedPathsMap[curKey] = 1;
prev[curKey] = 1;
}
}
return Object.keys(updateKeyedPathsMap);
return prev;
}

@@ -304,3 +339,3 @@ function runUpdates(currentState, updater, func) {

store._patchListeners.forEach(listener => listener(patches, inversePatches));
store._updateState(nextState, getChangedPathsFromPatches(patches));
store._updateState(nextState, Object.keys(getChangedPathsFromPatches(patches)));
}

@@ -392,2 +427,3 @@ }

}
console.log(`Clearing cache for [${key}]`);
delete clientAsyncCache.results[key];

@@ -427,5 +463,7 @@ notifyListeners(key);

}
const storeErrorProxy = new Proxy({}, {
get: function (obj, prop) {
throw new Error(`Pullstate: Trying to access store (${String(prop)}) inside async actions without the correct usage or setup.
let storeErrorProxy;
try {
storeErrorProxy = new Proxy({}, {
get: function (obj, prop) {
throw new Error(`Pullstate: Trying to access store (${String(prop)}) inside async actions without the correct usage or setup.
If this error occurred on the server:

@@ -437,15 +475,19 @@ * If using run(), make use of your created instance for this request: instance.runAsyncAction()

* Make sure you have created your "pullstateCore" object with all your stores, using createPullstateCore(), and are making use of instantiate() before rendering.`);
},
});
},
});
}
catch {
storeErrorProxy = {};
}
function createAsyncAction(action, { forceContext = false, shortCircuitHook, cacheBreakHook, postActionHook, subsetKey, } = {}) {
const ordinal = asyncCreationOrdinal++;
const onServer = typeof window === "undefined";
function _createKey(keyOrdinal, args, customKey) {
function _createKey(args, customKey) {
if (customKey) {
return `${keyOrdinal}-c-${customKey}`;
return `${ordinal}-c-${customKey}`;
}
if (subsetKey !== undefined) {
return `${keyOrdinal}-${keyFromObject(subsetKey(args))}`;
return `${ordinal}-${keyFromObject(subsetKey(args))}`;
}
return `${keyOrdinal}-${keyFromObject(args)}`;
return `${ordinal}-${keyFromObject(args)}`;
}

@@ -595,3 +637,3 @@ let cacheBreakWatcher = {};

const read = (args = {}, { cacheBreakEnabled = true, postActionEnabled = true, key: customKey } = {}) => {
const key = _createKey(ordinal, args, customKey);
const key = _createKey(args, customKey);
const cache = onServer ? useContext(PullstateContext)._asyncCache : clientAsyncCache;

@@ -644,3 +686,3 @@ const stores = onServer || forceContext

const prevKeyRef = useRef(".");
const key = dormant ? "." : _createKey(ordinal, args, customKey);
const key = dormant ? "." : _createKey(args, customKey);
let watchId = useRef(-1);

@@ -724,3 +766,3 @@ if (watchId.current === -1) {

const run = async (args = {}, { treatAsUpdate = false, ignoreShortCircuit = false, respectCache = false, key: customKey, _asyncCache = clientAsyncCache, _stores = clientStores.loaded ? clientStores.stores : storeErrorProxy, } = {}) => {
const key = _createKey(ordinal, args, customKey);
const key = _createKey(args, customKey);
if (respectCache) {

@@ -776,3 +818,3 @@ const cached = getCachedResult(key, _asyncCache, args, _stores, EPostActionContext.RUN_HIT_CACHE, true, true, false);

const clearCache = (args = {}, customKey) => {
const key = _createKey(ordinal, args, customKey);
const key = _createKey(args, customKey);
clearActionCache(key);

@@ -797,3 +839,3 @@ };

const { notify = true, key: customKey } = options || {};
const key = _createKey(ordinal, args, customKey);
const key = _createKey(args, customKey);
const cache = onServer ? useContext(PullstateContext)._asyncCache : clientAsyncCache;

@@ -810,3 +852,3 @@ cache.results[key] = [true, true, result, false, Date.now()];

const { notify = true, resetTimeCached = true, runPostActionHook: postAction = false, key: customKey } = options || {};
const key = _createKey(ordinal, args, customKey);
const key = _createKey(args, customKey);
const cache = onServer ? useContext(PullstateContext)._asyncCache : clientAsyncCache;

@@ -838,3 +880,3 @@ if (cache.results.hasOwnProperty(key) && !cache.results[key][2].error) {

const { checkCacheBreak = false, key: customKey } = options || {};
const key = _createKey(ordinal, args, customKey);
const key = _createKey(args, customKey);
let cacheBreakable = false;

@@ -908,3 +950,3 @@ const cache = onServer ? useContext(PullstateContext)._asyncCache : clientAsyncCache;

};
const use = (args, { initiate = true, ssr = true, postActionEnabled, cacheBreakEnabled, holdPrevious = false, dormant = false, key } = {}) => {
const use = (args, { initiate = true, ssr = true, postActionEnabled, cacheBreakEnabled, holdPrevious = false, dormant = false, key, } = {}) => {
if (postActionEnabled == null) {

@@ -1005,2 +1047,24 @@ postActionEnabled = initiate;

}
actionSetup() {
const actUpdateMap = {};
const updatedStores = new Set();
for (const store of Object.keys(clientStores.stores)) {
actUpdateMap[store] = updater => {
updatedStores.add(store);
clientStores.stores[store].batch(updater);
};
}
const action = action => action;
const act = (action) => {
updatedStores.clear();
action(actUpdateMap);
for (const store of updatedStores) {
clientStores.stores[store].flushBatch(true);
}
};
return {
action,
act,
};
}
createAsyncAction(action, options = {}) {

@@ -1007,0 +1071,0 @@ return createAsyncAction(action, options);

@@ -105,3 +105,3 @@ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});function _interopDefault(e){return(e&&(typeof e==='object')&&'default'in e)?e['default']:e}var isEqual=_interopDefault(require('fast-deep-equal/es6')),React=require('react'),React__default=_interopDefault(React),produce=require('immer'),produce__default=_interopDefault(produce);function useStoreState(store, getSubState, deps) {

store._patchListeners.forEach(listener => listener(patches, inversePatches));
return getChangedPathsFromPatches(patches);
return Object.keys(getChangedPathsFromPatches(patches));
}

@@ -162,2 +162,3 @@ }

this.currentState = nextState;
this.batchState = undefined;
for (const runReaction of this.reactions) {

@@ -244,4 +245,11 @@ updateKeyedPaths.push(...runReaction());

}
createPathReaction(path, reaction) {
}
getRawState() {
return this.currentState;
if (this.batchState !== undefined) {
return this.batchState;
}
else {
return this.currentState;
}
}

@@ -251,2 +259,30 @@ useState(getSubState, deps) {

}
act(action) {
action((u, p) => this.batch(u, p));
this.flushBatch(true);
}
batch(updater, patchesCallback) {
if (this.batchState === undefined) {
this.batchState = this.currentState;
}
const func = typeof updater === "function";
const [nextState, patches, inversePatches] = runUpdates(this.batchState, updater, func);
if (patches.length > 0 && (this._patchListeners.length > 0 || patchesCallback)) {
if (patchesCallback) {
patchesCallback(patches, inversePatches);
}
this._patchListeners.forEach(listener => listener(patches, inversePatches));
}
this.batchState = nextState;
}
flushBatch(ignoreError = false) {
if (this.batchState !== undefined) {
if (this.batchState !== this.currentState) {
this._updateState(this.batchState);
}
}
else if (!ignoreError) {
console.error(`Pullstate: Trying to flush batch state which was never created or updated on`);
}
}
update(updater, patchesCallback) {

@@ -263,7 +299,6 @@ update(this, updater, patchesCallback);

if (nextState !== currentState) {
store._updateState(nextState, getChangedPathsFromPatches(patches));
store._updateState(nextState, Object.keys(getChangedPathsFromPatches(patches)));
}
}
function getChangedPathsFromPatches(changePatches) {
const updateKeyedPathsMap = {};
function getChangedPathsFromPatches(changePatches, prev = {}) {
for (const patch of changePatches) {

@@ -278,6 +313,6 @@ let curKey;

}
updateKeyedPathsMap[curKey] = 1;
prev[curKey] = 1;
}
}
return Object.keys(updateKeyedPathsMap);
return prev;
}

@@ -304,3 +339,3 @@ function runUpdates(currentState, updater, func) {

store._patchListeners.forEach(listener => listener(patches, inversePatches));
store._updateState(nextState, getChangedPathsFromPatches(patches));
store._updateState(nextState, Object.keys(getChangedPathsFromPatches(patches)));
}

@@ -390,2 +425,3 @@ }

}
console.log(`Clearing cache for [${key}]`);
delete clientAsyncCache.results[key];

@@ -425,5 +461,7 @@ notifyListeners(key);

}
const storeErrorProxy = new Proxy({}, {
get: function (obj, prop) {
throw new Error(`Pullstate: Trying to access store (${String(prop)}) inside async actions without the correct usage or setup.
let storeErrorProxy;
try {
storeErrorProxy = new Proxy({}, {
get: function (obj, prop) {
throw new Error(`Pullstate: Trying to access store (${String(prop)}) inside async actions without the correct usage or setup.
If this error occurred on the server:

@@ -435,15 +473,19 @@ * If using run(), make use of your created instance for this request: instance.runAsyncAction()

* Make sure you have created your "pullstateCore" object with all your stores, using createPullstateCore(), and are making use of instantiate() before rendering.`);
},
});
},
});
}
catch {
storeErrorProxy = {};
}
function createAsyncAction(action, { forceContext = false, shortCircuitHook, cacheBreakHook, postActionHook, subsetKey, } = {}) {
const ordinal = asyncCreationOrdinal++;
const onServer = typeof window === "undefined";
function _createKey(keyOrdinal, args, customKey) {
function _createKey(args, customKey) {
if (customKey) {
return `${keyOrdinal}-c-${customKey}`;
return `${ordinal}-c-${customKey}`;
}
if (subsetKey !== undefined) {
return `${keyOrdinal}-${keyFromObject(subsetKey(args))}`;
return `${ordinal}-${keyFromObject(subsetKey(args))}`;
}
return `${keyOrdinal}-${keyFromObject(args)}`;
return `${ordinal}-${keyFromObject(args)}`;
}

@@ -593,3 +635,3 @@ let cacheBreakWatcher = {};

const read = (args = {}, { cacheBreakEnabled = true, postActionEnabled = true, key: customKey } = {}) => {
const key = _createKey(ordinal, args, customKey);
const key = _createKey(args, customKey);
const cache = onServer ? React.useContext(PullstateContext)._asyncCache : clientAsyncCache;

@@ -642,3 +684,3 @@ const stores = onServer || forceContext

const prevKeyRef = React.useRef(".");
const key = dormant ? "." : _createKey(ordinal, args, customKey);
const key = dormant ? "." : _createKey(args, customKey);
let watchId = React.useRef(-1);

@@ -722,3 +764,3 @@ if (watchId.current === -1) {

const run = async (args = {}, { treatAsUpdate = false, ignoreShortCircuit = false, respectCache = false, key: customKey, _asyncCache = clientAsyncCache, _stores = clientStores.loaded ? clientStores.stores : storeErrorProxy, } = {}) => {
const key = _createKey(ordinal, args, customKey);
const key = _createKey(args, customKey);
if (respectCache) {

@@ -774,3 +816,3 @@ const cached = getCachedResult(key, _asyncCache, args, _stores, exports.EPostActionContext.RUN_HIT_CACHE, true, true, false);

const clearCache = (args = {}, customKey) => {
const key = _createKey(ordinal, args, customKey);
const key = _createKey(args, customKey);
clearActionCache(key);

@@ -795,3 +837,3 @@ };

const { notify = true, key: customKey } = options || {};
const key = _createKey(ordinal, args, customKey);
const key = _createKey(args, customKey);
const cache = onServer ? React.useContext(PullstateContext)._asyncCache : clientAsyncCache;

@@ -808,3 +850,3 @@ cache.results[key] = [true, true, result, false, Date.now()];

const { notify = true, resetTimeCached = true, runPostActionHook: postAction = false, key: customKey } = options || {};
const key = _createKey(ordinal, args, customKey);
const key = _createKey(args, customKey);
const cache = onServer ? React.useContext(PullstateContext)._asyncCache : clientAsyncCache;

@@ -836,3 +878,3 @@ if (cache.results.hasOwnProperty(key) && !cache.results[key][2].error) {

const { checkCacheBreak = false, key: customKey } = options || {};
const key = _createKey(ordinal, args, customKey);
const key = _createKey(args, customKey);
let cacheBreakable = false;

@@ -906,3 +948,3 @@ const cache = onServer ? React.useContext(PullstateContext)._asyncCache : clientAsyncCache;

};
const use = (args, { initiate = true, ssr = true, postActionEnabled, cacheBreakEnabled, holdPrevious = false, dormant = false, key } = {}) => {
const use = (args, { initiate = true, ssr = true, postActionEnabled, cacheBreakEnabled, holdPrevious = false, dormant = false, key, } = {}) => {
if (postActionEnabled == null) {

@@ -1003,2 +1045,24 @@ postActionEnabled = initiate;

}
actionSetup() {
const actUpdateMap = {};
const updatedStores = new Set();
for (const store of Object.keys(clientStores.stores)) {
actUpdateMap[store] = updater => {
updatedStores.add(store);
clientStores.stores[store].batch(updater);
};
}
const action = action => action;
const act = (action) => {
updatedStores.clear();
action(actUpdateMap);
for (const store of updatedStores) {
clientStores.stores[store].flushBatch(true);
}
};
return {
action,
act,
};
}
createAsyncAction(action, options = {}) {

@@ -1005,0 +1069,0 @@ return createAsyncAction(action, options);

import React from "react";
import { Store } from "./Store";
import { Store, TUpdateFunction } from "./Store";
import { IAsyncActionRunOptions, ICreateAsyncActionOptions, IOCreateAsyncActionOutput, IPullstateAsyncActionOrdState, IPullstateAsyncCache, IPullstateAsyncResultState, TPullstateAsyncAction, TPullstateAsyncRunResponse } from "./async-types";

@@ -17,2 +17,3 @@ export interface IPullstateAllStores {

};
export declare type TMultiStoreAction<P extends PullstateSingleton, S extends IPullstateAllStores = P extends PullstateSingleton<infer ST> ? ST : any> = (update: TMultiStoreUpdateMap<S>) => void;
export declare class PullstateSingleton<S extends IPullstateAllStores = IPullstateAllStores> {

@@ -26,4 +27,11 @@ constructor(allStores: S);

useInstance(): PullstateInstance<S>;
actionSetup(): {
action: (update: TMultiStoreAction<PullstateSingleton<S>, S>) => TMultiStoreAction<PullstateSingleton<S>, S>;
act: (action: TMultiStoreAction<PullstateSingleton<S>, S>) => void;
};
createAsyncAction<A = any, R = any, T extends string = string>(action: TPullstateAsyncAction<A, R, T, S>, options?: ICreateAsyncActionOptions<A, R, T, S>): IOCreateAsyncActionOutput<A, R, T>;
}
declare type TMultiStoreUpdateMap<S extends IPullstateAllStores> = {
[K in keyof S]: (updater: TUpdateFunction<S[K] extends Store<infer T> ? T : any>) => void;
};
interface IPullstateSnapshot {

@@ -30,0 +38,0 @@ allState: {

import { Patch, PatchListener } from "immer";
import { DeepKeyOfArray } from "./useStoreStateOpt-types";
import { DeepKeyOfArray, TAllPathsParameter } from "./useStoreStateOpt-types";
export declare type TPullstateUpdateListener = () => void;

@@ -9,8 +9,12 @@ export interface IStoreInternalOptions<S> {

export declare type TUpdateFunction<S> = (draft: S, original: S) => void;
declare type TPathReactionFunction<S> = (paths: TAllPathsParameter<S>, draft: S, original: S) => void;
declare type TReactionFunction<S, T> = (watched: T, draft: S, original: S, previousWatched: T) => void;
declare type TRunReactionFunction = () => string[];
declare type TReactionCreator<S> = (store: Store<S>) => TRunReactionFunction;
export declare type TStoreActionUpdate<S> = (updater: TUpdateFunction<S> | TUpdateFunction<S>[], patchesCallback?: (patches: Patch[], inversePatches: Patch[]) => void) => void;
export declare type TStoreAction<S> = (update: TStoreActionUpdate<S>) => void;
export declare class Store<S = any> {
private updateListeners;
private currentState;
private batchState;
private readonly initialState;

@@ -40,5 +44,9 @@ private ssr;

createReaction<T>(watch: (state: S) => T, reaction: TReactionFunction<S, T>): () => void;
createPathReaction<T>(path: TAllPathsParameter<S>, reaction: TPathReactionFunction<S>): void;
getRawState(): S;
useState(): S;
useState<SS = any>(getSubState: (state: S) => SS, deps?: ReadonlyArray<any>): SS;
act(action: TStoreAction<S>): void;
batch(updater: TUpdateFunction<S> | TUpdateFunction<S>[], patchesCallback?: (patches: Patch[], inversePatches: Patch[]) => void): void;
flushBatch(ignoreError?: boolean): void;
update(updater: TUpdateFunction<S> | TUpdateFunction<S>[], patchesCallback?: (patches: Patch[], inversePatches: Patch[]) => void): void;

@@ -45,0 +53,0 @@ applyPatches(patches: Patch[]): void;

{
"name": "pullstate",
"version": "1.11.0",
"version": "1.11.1",
"description": "Simple state stores using immer and React hooks",

@@ -5,0 +5,0 @@ "main": "dist/index.js",

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc