Back to home

redux-toolkit/

react-basic-context-reducer

Version: 0.0.1

Last Updated: Unknown


Redux Reducer

Use this template to setup a helper for local React reducer management using Redux Toolkit.

Required

VariableData TypeInfo
namestringThe name of the reducer

Module files

1import * as React from "react";
2import { createSlice } from "@reduxjs/toolkit";
3
4type <%= _.upperFirst(_.camelCase(name)) %>Props = {
5 value: number;
6};
7
8/**
9 * Complex context to help manage local state.
10 *
11 * @returns {void} undefined response
12 */
13const <%= _.upperFirst(_.camelCase(name)) %>Context = React.createContext<Partial<<%= _.upperFirst(_.camelCase(name)) %>Props>>({});
14
15const initialState: <%= _.upperFirst(_.camelCase(name)) %>Props = {
16 value: 0,
17};
18const <%= _.camelCase(name) %>Slice = createSlice({
19 name: "<%= _.camelCase(name) %>",
20 reducers: {
21 increase: (state) => void (state.value += 1),
22 decrease: (state) => void (state.value -= 1),
23 },
24 initialState: initialState,
25});
26
27export const { increase, decrease } = <%= _.camelCase(name) %>Slice.actions;
28const <%= _.camelCase(name) %>Reducer = <%= _.camelCase(name) %>Slice.reducer;
29
30export function <%= _.upperFirst(_.camelCase(name)) %>Provider(props) {
31 const [cache, dispatch] = React.useReducer(<%= _.camelCase(name) %>Reducer, initialState);
32 const value = [cache, dispatch];
33
34 return <<%= _.upperFirst(_.camelCase(name)) %>Context.Provider value={value} {...props} />;
35}
36
37export function use<%= _.upperFirst(_.camelCase(name)) %>() {
38 const context = React.useContext(<%= _.upperFirst(_.camelCase(name)) %>Context);
39 if (!context) {
40 throw new Error("Requires <%= _.upperFirst(_.camelCase(name)) %>Provider");
41 }
42
43 return context;
44}

Install


Lift generate


Repository

https://github.com/okeeffed/pkg-lift-redux-toolkit

Sections