Easy way to map getState() to this.props.getState() for dependency injection?
See original GitHub issueHello.
I’m working on a piece of code called “reduxify” which I hope to publish as an NPM module, that helps take away some of the boilerplate of using react-redux on large projects.
The problem that I’m running into is that I can’t seem to find a way to map getState() to props. This is somewhat important for the design pattern I’m working with.
Specifically, in order to keep my “utilities” unit-testable in isolation - that is, without having to import the store, I was using dependency injection. That is, if I had a file called ./utilities/api.js, it would be written something like this:
export default function api = (dispatch, getState) => {
const getRandomNumber = (req) => {
request(req).then((num) => {
dispatch(addNumber(num));
let currentState = getState();
if (currentState.number % 2 === 0 ){
dispatch(evenAction())
} else {
dispatch(oddAction());
}
})
}
return {
getThingy,
}
}
This way, I can mock both dispatch and getState. As for the use in dev/production, it would be something like this:
import apiRoot from './api'
class NumberThing extends Component{
constructor(props){
let api = apiRoot(this.props.dispatch, this.props.getState)
}
this.handleClick(){
api.getThingy(this.state.whatever)
}
}
I’ll be writing v. 1 of Reduxify without this functionality, but I’m thinking there’s gotta be a way to do this without exporting getState() from the store and importing it into the component.
Your thoughts?
Issue Analytics
- State:
- Created 7 years ago
- Comments:7 (4 by maintainers)
Top GitHub Comments
Hi, Brian. I know we talked about something like this a while back. Is there any reason you aren’t just using thunks? Because thunks are middleware-based, the thunk functions receive
getState
anddispatch
automatically. Also, with the newer redux-thunk v2.1.0, you can automatically inject additional arguments into your thunk functions, such as specific AJAX API wrappers or something.Only that I’ve tried it, and it doesn’t work for whatever reason. I suspect it is because Redux Dev Tools attempts to recalculate the state from scratch by running through all the actions, every time you move backwards in the timeline, which is problematic for an application that can have up to 3000 actions.