How to execute api call with redux?

Viewed 151

I'm recently learn about react-redux. Now i'm bit stuck about how can i execute the api call.

Here is my action.ts

export const fetchEvent = () => async (
    dispatch: Dispatch
) => {
    dispatch({ type: ActionTypes.FETCH_EVENT_REQUEST });

    try {
        const response = await axios.get<EvenData[]>(
            `https://jsonplaceholder.typicode.com/todos/`
        );
        dispatch<FetchEventAction>({
            type: ActionTypes.FETCH_EVENT_SUCCESS,
            payload: response.data
        });

    } catch (error) {
        dispatch({ type: ActionTypes.FETCH_EVENT_FAILURE, error });
    }
};

and here is my event list and this is where i want call the api call

const mapStateToProps = (state: ActionTypes) => ({});
const dispatchProps = {};

type Props = ReturnType<typeof mapStateToProps> & typeof dispatchProps;

type State = {};

class EventList extends React.Component<Props, State> {
    componentDidMount() {
        // dispatch(fetchEvent());
    }

    render() {
        return (
            <section>
                <p>{ }</p>
            </section>
        );

    }
}

export default connect(
    mapStateToProps,
    dispatchProps
)(EventList);

So how can i make the api call ? inside my componentDidMount

1 Answers

you are missing the mapDispatchToProps , the one your are using is empty {}.

import {fetchEvent} from 'action.ts' // change to correct path

const mapStateToProps = (state: ActionTypes) => ({});
const mapDispatchToProps = (dispatch: Dispatch) => {
  return {
    fetchEvent: () => {
      dispatch(fetchEvent())
    }
  };
};

type Props = ReturnType<typeof mapStateToProps> & ReturnType<typeof mapDispatchToProps>;

type State = {};

class EventList extends React.Component<Props, State> {
    componentDidMount() {
        this.props.fetchEvent()
    }

    render() {
        return (
            <section>
                <p>{ }</p>
            </section>
        );

    }
}

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(EventList);
Related