@anhnh27/reduxtoolkit-action-dispatcher
TypeScript icon, indicating that this package has built-in type declarations

1.0.8 • Public • Published

reduxtoolkit-action-dispatcher

  • Dispatch redux actions without useDispatch or mapDispatchToProps.
  • Wait for your action.

Install

yarn add "@anhnh27/reduxtoolkit-action-dispatcher"

Setup

import actionDispatcherMiddleware from "@anhnh27/reduxtoolkit-action-dispatcher";
import { configureStore } from "@reduxjs/toolkit";
import counterReducer from "./counterSlice";

export const store = configureStore({
  reducer: counterReducer,
  middleware: (curryGetDefaultMiddleware) =>
    curryGetDefaultMiddleware().concat(actionDispatcherMiddleware),
});

// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>;
// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
export type AppDispatch = typeof store.dispatch;

Usage

//counterSlice.ts
import { createDispatcher } from "@anhnh27/reduxtoolkit-action-dispatcher";
import type { PayloadAction } from "@reduxjs/toolkit";
import { createSlice } from "@reduxjs/toolkit";

interface CounterState {
  value: number;
}

const initialState: CounterState = {
  value: 0,
};

export const counterSlice = createSlice({
  name: "counter",
  initialState,
  reducers: {
    incrementByAmount: (state, action: PayloadAction<number>) => {
      state.value += action.payload;
    },
    update: (state, action: PayloadAction<string>) => state,
  },
});

export const counterSlice = createSlice({
  name: "counter",
  initialState,
  reducers: {
    incrementByAmount: (state, action: PayloadAction<number>) => {
      state.value += action.payload;
    },
    update: (state, action: PayloadAction<string>) => state,
  },
});

export const counterDispatcher = createDispatcher(counterSlice);

const fakeApiRequest = () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, 3000);
  });
};

function* counterSagaWorker({ $result }: AnyAction) {
  yield call(fakeApiRequest);
  $result.value = true;
}

//Test.tsx
import { useEffect, useState } from "react";
import { ActivityIndicator } from "react-native";
import { counterDispatcher } from "./counterSlice";

const TestDispatcher = () => {
  const [loading, setLoading] = useState(true);
  useEffect(() => {
    (async () => {
      await counterDispatcher.update("Hello wolrd").$result;
      setLoading(false);
    })();
  }, []);

  useEffect(() => {
    counterDispatcher.incrementByAmount(10);
  }, []);

  if (loading) {
    return <ActivityIndicator size={"large"} />;
  }

  return null;
};

export default TestDispatcher;

Package Sidebar

Install

npm i @anhnh27/reduxtoolkit-action-dispatcher

Weekly Downloads

37

Version

1.0.8

License

MIT

Unpacked Size

10.1 kB

Total Files

13

Last publish

Collaborators

  • anhnh27