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

tquinlan92-typescript-redux-utils

v1.13.14

Published

typescript redux and react utilities

Downloads

67

Readme

tquinlan92-typescript-redux-utils

This package gives a few useful type-safe redux, react-redux, and react utilities.

makeNestedStore

makeNestedSimpleStore creates a nested redux store with thunk actions. It gives back reducers to use with combineReducers and actions to update the state. The actions include simpleActions to change the state with the same name as the state properties. It also includes methods set, to set a partial state with type checking, setAll to set the state with type checking, reset to reset a state to its initial state, resetAll to reset the state whole to its initial state.

The second parameter takes middleware to apply to the store returned.

export const {
    actions,
    reducers, 
    selectors,
    initalState,
    reducer,
    store
} =
    makeNestedStore(initialStates, [/* middleware */]);

The code below this shows the full basic usage. There's also a typescript create-react-app, redux, and redux thunk usage starting with ./src/index.tsx demonstrating the usage in a real app. The app example is just a create-react-app with typescript and the instructions can be found here here.

Also you can access a sandbox using it without typescript here.

import { combineReducers, createStore, applyMiddleware, AnyAction } from 'redux';
import {mergeStateWithActions, makeNestedStore } from 'tquinlan92-typescript-redux-utils';
import thunk, { ThunkAction } from 'redux-thunk';
import { createSelector } from 'reselect';

const state1 = mergeStateWithActions(
    {
        input: '',
        results: [] as string[],
    }, 
    {
        
        immerInput: (state, {value}: {value: string}) => {
            state.input = value;
        }
    }
);

const initialStates = {
    state1,
};

const state1ThunkActions = {
    getResults
};

export const { actions: storeActions, reducers, selectors, initalState, reducer, store } = 
makeNestedStore(initialStates, [thunk, logger]);

export type AppState = typeof initalState;

function getResults(): ThunkAction<void, AppState, void, AnyAction> {
    return async (dispatch) => {
        dispatch(actions.state1.results(['item1', 'item2', 'item3']))
    };
}

const thunkActions = {
    state1: state1ThunkActions
};

// Create a Selector using a exported selectors
function mapResults(results: string[]) {
    times(1000, () => {
        console.log('heavy computation');
    });
    return results.map(result => result);
}

const getResultsSelector = createSelector(
    selectors.state1.results,
    mapResults
)

// Tests demonstrationg the usage of the actions
describe('dispatching state1 actions', () => {
    describe('when state1.input is dispatched', () => {
        it('should set the state1.input value', () => {
            store.dispatch(actions.state1.input('newValue'));
            const newState = store.getState();
            expect(newState).toEqual({
                state1: {
                    input: 'newValue',
                    results: []
                }
            })
        })
    });
    describe('when state1.resetAll is dispatched', () => {
        it('should reset the state1 state to its initial state', () => {
            store.dispatch(actions.state1.resetAll());
            const newState = store.getState();
            expect(newState).toEqual({
                state1: {
                    input: '',
                    results: []
                }
            })
        })
    });
    describe('when state1.set is dispatched', () => {
        it('should update the properties on state1', () => {
            store.dispatch(actions.state1.set({input: 'newValueFromSet'}));
            const newState = store.getState();
            expect(newState).toEqual({
                state1: {
                    input: 'newValueFromSet',
                    results: []
                }
            })
        })
    });
    describe('when state1.setAll is dispatched', () => {
        it('should update the properties on state1', () => {
            store.dispatch(actions.state1.setAll({input: 'newValueFromSetAll', results: ['item1']}));
            const newState = store.getState();
            expect(newState).toEqual({
                state1: {
                    input: 'newValueFromSetAll',
                    results: ['item1']
                }
            })
        })
    });
    describe('when state1.reset is dispatched', () => {
        it('should reset the properties in params', () => {
            store.dispatch(actions.state1.results(['result1', 'result2', 'result3']));
            store.dispatch(actions.state1.reset(['results']));
            const newState = store.getState();
            expect(newState).toEqual({
                state1: {
                    input: 'newValueFromSetAll',
                    results: []
                }
            })
        })
    });
});

mergeStateWithActions

mergeStateWithActions takes two parameters intialState and otherActions. otherActions are reducers that will be typed to to the initialState passed and the second parameter to the reducer (the action type) will be typed for the action creator returned when used with makeNestedStore

import { mergeStateWithActions } from 'tquinlan92-typescript-redux-utils` 

const state1 = mergeStateWithActions(
    {
        input: '',
        results: [] as string[],
    }, 
    {
        
        immerInput: (state, {value}: {value: String}) => {
            state.input = value;
        })
    }
});

createConnectProps

createConnectProps takes a AppState as a generic type. It returns back a method to create connected props using mapStateToProps and mapDispatchToProps as its two parameters.

function createConnectProps<AppState>(): <MapStateToProps extends (state: AppState, ownProps: any) => {}, MapDispatchToProps extends MapDispatchToPropsParam<{}, {}>>(mapStateToProps: MapStateToProps, mapDispatchToProps?: MapDispatchToProps) => (Component: React.FunctionComponent<ReturnType<MapStateToProps> & MapDispatchToProps>) => {
    Component: React.FunctionComponent<ReturnType<MapStateToProps> & MapDispatchToProps>;
    mapStateToProps: MapStateToProps;
    mapDispatchToProps: MapDispatchToProps;
    Connected: import("react-redux").ConnectedComponentClass<(props: any) => React.ReactElement<any, string | ((props: any) => React.ReactElement<any, string | any | (new (props: any) => React.Component<any, any, any>)> | null) | (new (props: any) => React.Component<any, any, any>)>, Pick<any, never> & Parameters<MapStateToProps>[1]>;
};

Usage of connectProps

import React from 'react';
import { actions, createConnectProps, AppState } from "./store";

const connectProps = createConnectProps<AppState>();

const connectedProps = connectProps(
    (state, {valueFromProp}: {valueFromProp: string;}) => {
        const { input, results } = state.state1;
        return {
            input,
            results,
            valueFromProp
        }
    }, 
    {
        onChange: actions.state1.input,
        getResults: actions.state1.getResults,
        reset: actions.state1.reset
    });

export const { Connected: State1ComponentConnected } = connectedProps(
    { input, results, onChange, getResults, reset, classes, valueFromProp }) => {
        return (
            <>
                <input value={input} onChange={event => onChange(event.target.value)} />
                <button onClick={getResults} className={classes.button}> {valueFromProp} </button>
                <button onClick={reset}>Reset</button>
                <ul>
                    {results.map(result => {
                        return <li>{result}</li>
                    })}
                </ul>
            </>
        )
    })
)

withStyles

StyleComponent creates a component with JSS styles given as props

Usage of withStyles

import { withStyles, WithStyles } from './tquinlan92-typescript-redux-utils';

const styles = {
    button: {
        background: 'green'
    }
}

const ComponentWithoutStyles: React.FC<WithStyles<typeof styles>>({classes}) {
    return <button className={classes.button} />
}

const StyledComponent2 = withStyles({button: {background: 'green'}})({classes}) => {
    return <button className={classes.button} />
})