I'm trying to use getState function in async action. I'm working in React with Typescript and middleware redux-thunk. I've added argument with getState as a second argument like below:
export const fetchPostsAndUsers = () => async (
dispatch: ThunkDispatch<State, unknown, Action>,
getState: () => State
) => {
await dispatch(fetchPosts());
const userIds: number[] = Array.from(
new Set(getState().posts.map((post: Post) => post.userId))
);
userIds.forEach((id) => dispatch(fetchUser(id)));
};
But I have a problem in connected component with typing this getState. Look below:
interface ConnectedProps {
createStream: (formValues: IStream, getState?: () => State) => void;
}
const StreamCreate = (
props: InjectedFormProps<IStream, ConnectedProps> & ConnectedProps
) => {
const onSubmit = (formValues: IStream) => {
props.createStream(formValues);
};
const classes = useStyles();
return (
<Container maxWidth="sm">
<form
className={classes.root}
style={{ marginTop: "100px" }}
onSubmit={props.handleSubmit(onSubmit)}
>
<Field name="title" label="Enter Title" component={renderInput} />
<Field
name="description"
label="Enter description"
component={renderInput}
/>
<Button
variant="contained"
color="primary"
type="submit"
style={{ marginLeft: "10px" }}
>
Submit
</Button>
</form>
</Container>
);
};
const formWrapped = reduxForm<IStream, ConnectedProps>({
form: "streamCreate", // name of using form
validate,
})(StreamCreate);
const mapDispatchToProps = (dispatch: Dispatch) => {
return bindActionCreators(
{
createStream,
},
dispatch
);
};
export default connect(null, mapDispatchToProps)(formWrapped);
Error is in the last line:
export default connect(null, mapDispatchToProps)(formWrapped);
Like on the screen below:
How can I avoid this error? What is the correct type for getState function in this case? I would be grateful for help.
Ok, sorry It was my fault. I incorrectly passed getState. Should be in return function: