-1

I need to access to my store outside component (from a classic function), but when I try to call getState(), I have an error:

Property 'getState' does not exist on type '(initialState: any) => any'

Here is my store declaration and import:

store.ts

import storeHolder from '@lib/storeHolder';
import rootReducer from './rootReducer';
import rootSaga from './rootSaga';

const bindMiddleware = (middleware: any) => applyMiddleware(...middleware);
const composeEnhancers = (typeof window !== 'undefined' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__) || compose;

function configureStore(initialState: any) {
  const sagaMiddleware = createSagaMiddleware();
  const store = createStore(rootReducer, initialState, composeEnhancers(bindMiddleware([sagaMiddleware]))) as any;

  store.sagaTask = sagaMiddleware.run(rootSaga);

  storeHolder.setStore(store);

  return store;
}

export default configureStore;

file-where-i-need.ts

import store from '@redux/store';
import moment from 'moment';

export function formatDateFromnow(date: Date) {
  const state = store.getState(); <-- error: Property 'getState' does not exist on type '(initialState: any) => any'

  const { locale } = state.theme.locale;  

  return moment(date).locale(locale).fromNow();
}

Any idea of what I did wrong? I read a lot of posts about this, but did not find a solution.

2
  • 1
    store.js doesn't export a store, it exports a function that creates the store, so you cannot just call getState on it. You need to get the actual store instance that is returned from this function and that I assume you pass to <Provider> in your root react component. Since you use nexttjs, it is probably a bad idea to try and export the store from some file. A common practice is not accessing the store from non-component function, instead add a parameter locale to formatDateFromnow and retrieve it from the store in the component that uses formatDateFromnow Commented Sep 4, 2023 at 18:05
  • Thank you @AlexChashin, it's this, I imported it from storeHolder and all works. Commented Sep 5, 2023 at 9:54

1 Answer 1

0

I suggest you to transform your fileINeed to a React hook

const useSomethingINeed = () => {
     const state = something// get your state as inside a component

     const { locale } = state.theme.locale

     return {
         format: date => moment(date).locale(locale).fromNow();
     }
}

And use it inside your wanted component

const MyWantedComponent = () => {
    const something = useSomethingINeed()
   
    const myDate = new Date();
    
    const myProcessedDate = something.format(myDate)

    return (<>something</>)
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.