Using getState in redux-thunk async action

2.2k Views Asked by At

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:

enter image description here

How can I avoid this error? What is the correct type for getState function in this case? I would be grateful for help.

1

There are 1 best solutions below

0
On

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 });
  };
};