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

rtk-slice-transformer

v2.0.0

Published

A Redux Toolkit slice transformer helpers with side effects reducer.

Downloads

6

Readme

npm npm npm bundle size

rtk-slice-transformer

This package creates a simplified interface for transforming a slice, or slices, as well as any associated actions, and then performing side effects on the transformed output via an enhancer. The main point is simplicity, but we also keep previous state in memory to avoid having to call every transformer on every single dispatch. If holding a reference to previous state in memory is problematic for you, please do not use this.

Use cases for this functionality might include tools like Sentry, or other analytics, where you want to shoot off breadcrumbs or state, but need to strip out Personally Identifiable Information (PII) or other sensitive data.

Requirements

  • TypeScript 4.1+ (if you use TypeScript)
  • @reduxjs/toolkit 1.7+

Types currently use new TypeScript (currently 4.5), but may be compatible with older versions. Open an issue if you're having trouble. You'll at least need support for mapped types with key remapping (TS 4.1).

Installation

yarn add rtk-slice-transformer

Usage

rtk-slice-transformer exports a few functions that can be used alone or in combination to help simplify transformations. Below is a straightforward example of how you might structure this.

Example

// example.slice.ts
import { createSliceTransformer, stripPayload } from 'rtk-slice-transformer'
import { createSlice, PayloadAction } from '@reduxjs/toolkit'

type ExampleState = { readonly foo: string; readonly sensitive: number | null }
const initialState: ExampleState = { foo: '', sensitive: null }
export const exampleSlice = createSlice({
	name: 'example',
	initialState,
	reducers: {
		setFoo(s, a: PayloadAction<string>) {
			s.foo = a.payload
		},
		setSensitive(s, a: PayloadAction<number | null>) {
			s.sensitive = a.payload
		},
	},
})

export const { setFoo, setSentitive } = exampleSlice.actions

export const exampleTransformer = createSliceTransformer(
	exampleSlice,
	// Use some sanitizer function to clean the sensitive state
	(exampleState) => ({
		...exampleState,
		sentitive: sanitizeSensitiveSomehow(exampleState.sentitive),
	}),
	// Stripe sensitive payload from sensitive actions. Otherwise, just return the action.
	(action) => (setSentitive.match(action) ? stripPayload(action) : action),
)
// store.ts
import { combineTransformers, createReduxTransformer } from 'rtk-slice-transformer'
import { exampleTransformer } from './example.slice'
import { configureStore } from '@reduxjs/toolkit'

const stateTransformer = combineTransformers([exampleTransformer /*...additionalTransformers*/])

export const store = configureStore({
	// reducer, preloadedState, etc...
	enhancers: [
		createReduxTransformer(stateTransformer, (transformedAction, transformedState) => {
			// Do something with transformed stuff
		}),
	],
})

createSliceTransformer(slice, stateTransformer, actionTransformer?)

Pass in the slice as well as a stateTransformer function. stateTransformer will be passed the slice state, and you should return the transformed state from it.

You can also pass an actionTransformer. This function is not tied to the slice explicitly, and it may receive any action. However, it is often convenient to define this logic in the same place as other slice-related code, and this API will copy it to the output of createSliceTransformer.

combineTransformers(transformers, actionTransformer? = DEFAULT_COMBINED_ACTION_TRANSFORMER)

A list of transformers and combines them into a single transformer. Currently, the returned result is different from the result of createSliceTransformer, since it doesn't include the slice name. If desirable, we could allow combineTransformers to accept a name, and thus return a type that allows arbitrary levels of combination. Open a PR if you need this. Currently, you could do the same thing, but you'd have to add a name to the output and coerce the type.

Additionally, combineTransformers may take an optional actionTransformer that acts on the global actions. The default combined transformer will strip the payload from any RTK thunk types (fulfilled|pending|rejected), since these are likely to contain a significant amount of unwanted data. If you want RTK actions, simply pass an identity function: combineTransformers(transformers, (action) => action).

NOTE ABOUT ACTION TRANSFORMERS:

Action transformers are called one after another until a transformer returns something that does not strictly equal the original action. Thus, the first transformer that does a transformation on an action "wins", and the rest are ignored. An obvious consequence of this is that, if you don't want to transform an action, you must return the original action. We currently do not check for undefined, so if you return nothing, the action will be transformed to undefined. If there's a good reason to consider undefined as "not transformed", we could make that distinction, but currently we don't.

createReduxTransformer(transformer, sideEffectsCb, onError?)

A dead simple enhancer creator that takes in the combined transformer for the state, a side effects callback, and an optional error handler.

sideEffectsCb takes the form sideEffectsCb(transformedAction, transformedState), and you can use this to do whatever you want with these values. Note, that if the action or state is not transformed (i.e. it's the original action or state), you'll have to abide the same immutable constraints as with any redux action or state. Probably best to treat these as immutable.

The optional onError handler can be passed in case any of the transformers throw.

stripPayload(action)

A helper for the common task of stripping the payload from an action.

combineActionTransformers(transformers)

A helper used by combineTransformers. Takes in a list of transformers and returns a single transformer. This is useful if you want to break up your action transformers into multiple functions and then pass the combined result to createSliceTransformer or combineTransformers. E.g. if you still want to filter RTK thunk actions, but want to add something of your own:

import {
	combineActionTransformers,
	DEFAULT_COMBINED_ACTION_TRANSFORMER,
} from 'rtk-slice-transformer'

const rootActionTransformer = combineActionTransformers([
	DEFAULT_COMBINED_ACTION_TRANSFORMER,
	mySpecialRootTransformer,
])

All the same caveats apply as mentioned above.