Home > OS >  How to access Redux store outside React components with Typescript
How to access Redux store outside React components with Typescript

Time:12-14

I want fetch some state from my store in one of the utils functions that I have. I know that I can do something like that:

import { store } from '../Store';
const func() {
    const state = store.getState()
}

Now, this gives me access to the whole store furthermore, when I try to access the elements in my store I don't get autocompletion like I get when I use useSelector hook. I wanted to know if there's anyway that I can actually get autocompletion or get access to only something specific when I access the store outside a component.

Maybe something like this: (I know it doesn't work, but I just want to know if there' something like this that I can do)

store<SomeTypeInMyStore>.getState()

This how my store is constructed:

const persistConfig :any = {
  key: 'root',
  storage: AsyncStorage,
  whitelist: ['login', 'biometrics']
};

const persistedReducer = persistReducer(persistConfig, reducers);

const store: Store<any> = createStore(
  persistedReducer,
  applyMiddleware(thunk)
);

const persistor = persistStore(store);

export { store, persistor };

CodePudding user response:

The first problem is the use of : Store<any>. Your code is telling TS "this is a generic store instance without any details about the state". Don't do that :) Instead you should follow our recommended TS setup guidelines, by inferring the type of the store and its state from the created instance:

// app/store.ts

const store = configureStore({
  reducer: {
    posts: postsReducer,
    comments: commentsReducer,
    users: usersReducer
  }
})

// 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

// and if you need the type of the store itself
export type AppStore = typeof store

Additionally, you should not import the store directly into other files, because that is likely to cause circular import issues.

Our first suggestion here would be to write those util functions so that they accept either the entire store state or just the needed values as arguments, so that they don't have to have access to the store instance. Failing that, if they must have access to the store itself, then we recommend injecting the store at app setup time.

  • Related