2

I have a React app with Redux and Redux Toolkit. Until now I only used redux-related code in React components using useDispatch and useSelector.

Now I want to update the Redux store from a pure JavaScript module. The actual module saves user data (notes, rewards for example) into an IndexedDB. I would like to update my redux store as well from this module. However, as it is not a React component I can not use useDispatch.

I have created a slice like this:

const initialState = {
    rewards: []
};

export const rewardSlice = createSlice({
    name: 'reward',
    initialState: initialState,
    reducers: {
        setRewards: (state, action) => {
            state.rewards = action.payload.rewards;
        },
        addReward: (state, action) => {
            state.rewards = [action.payload.reward, ...state.rewards];
        },
    },
});

export const { setRewards, addReward } = rewardSlice.actions;

export default rewardSlice.reducer;

And what I want is the equivalent of this code without using react hooks:

const dispatch = useDispatch();
dispatch(addReward({ reward: userReward }));

1 Answer 1

1

If you have a configStore.js file or the likes where you have used configureStore(), you can use the assigned constant using this method and import in the file where you need to call the dispatch() function

for example, supposing your reducers are configured in an exported constant called store:

//Assuming the file name is configStore.js and 
//configureStore is assigned to store
import {configureStore} from '@reduxjs/toolkit';

export default store = configureStore({
      reducer: persistedReducer,
      middleware: getDefaultMiddleware =>
        getDefaultMiddleware({
          serializableCheck: {
            ignoredActions: [
              FLUSH,
              REHYDRATE,
              PAUSE,
              PERSIST,
              PURGE,
              REGISTER,
            ],
          },
        }),
    });

now in the file where you need to dispatch() to store, simply import store. And then destructure from it the dispatch function

import store from './path_to/configStore';
.
.
.
const {dispatch} = store;
dispatch(addReward({ reward: userReward }));
Sign up to request clarification or add additional context in comments.

1 Comment

Can we do the same thing using an endpoint created by createApi from toolkit ? Because I can't find how to call an endpoint outside an hook.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.