1

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 };
1
  • I think that the purpose of utils functions is re-usability or DRY ( Don't Repeat Yourself). Why not use React Hook and still have the freedom to use either useSelector or useStore. Commented Dec 13, 2021 at 14:50

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

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.