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:
export const createStream = (formValues: IStream) => {
return async (dispatch: ThunkDispatch<void, State, Action>, getState: () => State) => {
const userId = getState().auth.userId;
const response: AxiosResponse<Stream> = await streams.post<Stream>('/streams', {...formValues, userId});
dispatch({type: ActionType.CREATE_STREAM, payload: response.data})
}
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.