Home > Back-end >  Using redux in an app with store defined in a javascript module and used in a typescript module
Using redux in an app with store defined in a javascript module and used in a typescript module

Time:03-12

I inherited an app that has JavaScript modules and TypeScript modules, and is using redux.
Unfortunately, I never used TypeScript :(

  • The state is defined in a .js module.
  • All modules that are using the state are also .js modules.
  • Now I need to access the state in a .ts module.

How can I do that?

This is the definition of my state in a file called uiReducer.js:

export default function uiReducer(state = new UiState, action) {
  switch(action.type) {
...

And it is used in multiple .js modules like in the following example:

const mapStateToProps = state => {
  return {
    a: state.get('ui').get('a'),
    b: state.get('ui').get('b')
  }
}

const mapDispatchToProps = dispatch => {
  return {
...
  }
}

export var About =
  connect(mapStateToProps, mapDispatchToProps)(About_Class);

As I wrote above, I would like to use it in a .ts module. Can you tell me how I do that?

I cannot provide full access to the source code, since I don't own it. But I can add info that is needed.

CodePudding user response:

I would assume that you're using class components, so the solution I would provide is for that.

First step is to import ConnectedProps:

import { connect, ConnectedProps } from 'react-redux'

Next step is to define the objects that your state/reducer, so in a file that we can name TsConnector.ts, add something like:

interface UIState {
    a: string,
    b: string,
    ...your other props
}

interface State {
    UI: UI,
    ...your other props
}

Then create your mapState and mapDispatch functions:

const mapState = (state: UIState ) => ({
   UI: state.UI,
   ...your other props
})

const mapDispatch = {
   ... your dispatch action
}

And export:

export default tsconnector = connect(mapState, mapDispatch)

Then use this as you normally would an HOC component:

import { tsconnector } from '../components/TsConnector'

export var About =
  tsconnector(mapStateToProps, mapDispatchToProps)(About_Class);

And that's it.

CodePudding user response:

Have you tried useDispatch and useSelector in ts file to get redux state

import {
useSelector as useReduxSelector,
TypedUseSelectorHook,
} from 'react-redux'


export const useSelector: TypedUseSelectorHook<RootState> = useReduxSelector
  • Related