I'm working on my first project using React + Redux and am encountering few issues when I try to dispatch a function in the componentDidMount part. I tried to follow the Reddit API example project in the docs but as they use JavaScript and I'm using TypeScript not quite everything is the same.
This is the React component where I'm trying to achieve this:
export class EducationComponent extends Component {
constructor(props: any) {
super(props);
}
componentDidMount() {
const { dispatch, getUser } = this.props;
dispatch(getUser());
}
public render() {
return (
<Content className="component">
<Demo/>
</Content>
);
}
}
function mapStateToProps(state: State) {
const { isLoaded, isFetching, user } = state.userProfile;
return {
user,
isFetching,
isLoaded
}
}
export default connect(mapStateToProps)(EducationComponent)
export const Education = (EducationComponent);
I'm receiving following error in the const { dispatch, getUser } = this.props;
line:
Error:(16, 17) TS2339: Property 'dispatch' does not exist on type 'Readonly<{}> & Readonly<{ children?: ReactNode; }>'.
Error:(16, 27) TS2339: Property 'getUser' does not exist on type 'Readonly<{}> & Readonly<{ children?: ReactNode; }>'.
The project can be found here if there are any uncertainties: https://github.com/jLemmings/GoCVFrontend
Is this the right way to get this done or are there better options?
Thanks
EDIT with current state:
const {Content} = Layout;
export class EducationComponent extends Component {
constructor(props: any) {
super(props);
}
componentDidMount() {
this.props.userAction();
}
public render() {
return (
<Content className="component">
<Demo/>
</Content>
);
}
}
const mapDispatchToProps = (dispatch: Dispatch) => bindActionCreators({
userAction: action.getUser,
}, dispatch);
function mapStateToProps(state: State) {
const { isLoaded, isFetching, user } = state.userProfile;
return {
user,
isFetching,
isLoaded
}
}
export default connect(mapStateToProps, mapDispatchToProps)(EducationComponent)
FINAL EDIT (got it working):
interface MyProps {
getUser: () => void
}
interface MyState {
userAction: ThunkAction<Promise<void>, {}, {}, AnyAction>
}
export class EducationComponent extends Component<MyProps, MyState> {
static defaultProps = {getUser: undefined};
constructor(props: any) {
super(props);
}
componentDidMount() {
this.props.getUser()
}
public render() {
return (
<Content className="component">
<Demo/>
</Content>
);
}
}
const mapDispatchToProps = (dispatch: ThunkDispatch<{}, {}, any>, ownProps: MyProps) => {
return {
getUser: () => {
dispatch(getUser());
}
}
}
function mapStateToProps(state: State) {
const {isLoaded, isFetching, user} = state.userProfile;
return {
user,
isFetching,
isLoaded
}
}
export default connect(mapStateToProps, mapDispatchToProps)(EducationComponent)