Async dispatch call in typescript from presentation component
Async dispatch call in typescript from presentation component
here in this tutorial https://redux.js.org/advanced/exampleredditapi in the section containing containers/AsyncApp.js
they have code that looks like
containers/AsyncApp.js
componentDidMount()
const dispatch, selectedSubreddit = this.props
dispatch(fetchPostsIfNeeded(selectedSubreddit))
but I don't know what they are doing here. I am trying to follow their example except in a project with typescript. Currently i get this runtime error from the chrome console
Uncaught TypeError: dispatch is not a functon
at ProxyComponent.componentDidMount (MyComponent.tsx?23ad:27)
My component code looks like this
export interface MyProps
prop1: any
type MyComponentProps = MyProps & DispatchProp;
class MyComponent extends React.Component<MyComponentProps, MyState>
componentDidMount()
const dispatch = this.props;
dispatch(fetchAsyncData());
render()
return (
<div>
</div>
);
export MyComponent ;
The dispatch function is meant to call an async action in my redux code. I tried including something called DispatchProps to obtain the dispatch function in my props, but it clearly hasn't worked. Where does this dispatch function come from?
connect
connect
1 Answer
1
Where are you defining your dispatch
function? Are you doing it using connect?
Regardless, you need to define your DispatchProp interface like you did with MyProps
dispatch
export interface MyProps
prop1: any
export interface DispatchProp
dispatch: () => void // unsure what the actual type of your dispatch function is
type MyComponentProps = MyProps & DispatchProp;
...
If you're trying to use connect to define your props, it would look something like this
function mapDispatchToProps(dispatch: Dispatch<any>): DispatchProp
return
dispatch: () =>
dispatch( type: "some_action_type", payload: somePayload)
;
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Where does this dispatch function come from? - from
connect
. There's noconnect
in the code you've posted. It's unclear what happens with MyComponent next but you likely don't connect it.– estus
Sep 7 '18 at 1:15