Thess
Thess

Reputation: 93

Can't dispatch action in class component

// action
export const getEvents = () => async (dispatch) => {
  try {
    dispatch({ type: GET_EVENTS_REQUEST })
    const data = await axios.get('http://localhost:5000/api/schedule').then((response) => response.data)
    dispatch({ type: GET_EVENTS_SUCCESS, payload: data })
  } catch (error) {
    dispatch({
      type: GET_EVENTS_FAIL,
      payload:
      error.response && error.response.data.message
        ? error.response.data.message
        : error.message,
    })
  }
}

// reducer
export const getEventsReducer = (state = { event: [] }, action) => {
  switch (action.type) {
  case GET_EVENTS_REQUEST:
    return { loading: true }
  case GET_EVENTS_SUCCESS:
    return { loading: false, event: action.payload }
  case GET_EVENTS_FAIL:
    return { loading: false, error: action.payload }
  default:
    return state
  }
}

// and this is how I'm trying to call my action:
import { getEvents } from '../../redux/actions/calendarActions'

class Calendar extends React.PureComponent {
    componentDidMount() {
        const { dispatch } = this.props
        console.log(dispatch(getEvents()))
    }
}
export default connect()(Calendar)
// component is much bigger, I only added relevant parts

Up until my reducer, if I console.log my data, it is correct, as well as in my redux dev tools tab: an array with a few entries. But when console.logging in my Calendar component, it returns a promise, with undefined result:

Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: undefined

What am I doing wrong?

Upvotes: 0

Views: 855

Answers (1)

Erfan
Erfan

Reputation: 1812

Normally you want to have access to either the dispatch or the store of Redux within a component. you already have the dispatch function within the component, but if you need access to Redux state inside it:

first you need to define such function, which makes the redux store available in the component.

    const mapStateToProps = (state) => ({
  state: state // a "state" prop is available in the component which points to redux state, 
})

or you can customize it if you only need certain properties of Redux state:

        const mapStateToProps = (state) => ({
  state: state.event // 
})

and change the connect function like this:

connect(mapStateToProps)(Calendar)

Upvotes: 1

Related Questions