Morton
Morton

Reputation: 5782

How to get redux store value without component?

I want to get store value directly in my action file.

Here is my reducer file

ServiceReducer.js

import {
  // other actions
  RESET_SERVICE_UPDATE_STATUS
} from '../actions/types';

const INITIAL_STATE = {
  serviceData: [],
  modalVisable: false, 
  modalMsg: '',
  updateStatus: null
};

export default (state = INITIAL_STATE, action) => {
  switch (action.type) {
    // the other actions
    case RESET_SERVICE_UPDATE_STATUS:
      return {
        ...state,
        updateStatus: action.updateStatus
      };
    default:
      return state;
    }
};

Here is my action file

ServiceAction.js

// I try to import the reducer
import ServiceReducer from '../reducers/ServiceReducer';
import { 
  // other actions
  RESET_SERVICE_UPDATE_STATUS
} from './types';

export const resetServiceUpdateStatus = () => {
  return (dispatch) => {
    console.log('What is ServiceReducer', ServiceReducer);
    // dispatch({ type: RESET_SERVICE_UPDATE_STATUS, updateStatus: null });
  };  
};

I console.log the reducer, I can't see any store value that I can get.

enter image description here

Here is my reducer file index.js

import { combineReducers } from 'redux';
// other reducers
import ServiceReducer from './ServiceReducer';

export default combineReducers({
  // other reducer
  ServiceRedux: ServiceReducer
});

I try the code in my action, but just get original initial state value.

import { createStore } from 'redux';
import reducers from '../reducers';

const store = createStore(reducers);

console.log('what is store', store.getState());

Any help would be appreciated. Thanks.

Upvotes: 1

Views: 1575

Answers (1)

lavor
lavor

Reputation: 1877

You can use Redux without React. react-redux is just API for easier manipulation with Redux in React.

You should create your store in separate file, e.g. store.js:

import { createStore } from 'redux';
import reducers from '../reducers';

const store = createStore(reducers);

export default store;

And then whenever you need your state of the store, import store from store.js and call store.getState():

some js file:

import store form './store';

// get current state
console.log('what is currently in store', store.getState());

Upvotes: 2

Related Questions