Search code examples
reactjsreduxactiondispatch

React Component receives the Redux states but can't dispatch actions


The action I want to trigger works on its own, the axis request works and it retrieves data from an api. However when I try to run it from the component using connect and then accessing it as a prop, it is like the function doesn't run, and the redux state don't update accordingly.

This is how I use connect with my react component (getChannels is imported before from the action js file

const mapStateToProps = (state) => ({
  channels: state.Channels.channels,
})

export default connect(mapStateToProps,{ getChannels })(ChannelList)

This is how I call the function inside the component

componentDidMount(){

    this.props.getChannels
   
  }

When I log the props to the console I get the initial redux states, and a function object.

console log image

I have tried different ways of dispatching the action but I am new to this so I can't identify why it doesn't work. Below is my action file

import axios from 'axios'

import { GET_CHANNELS } from "./types";


// GET CHANNELS

export const getChannels = () => (dispatch) => {

 
 axios
  .get('/TeamChat/RetrieveChannels')
  .then((res) => {
    console.log(res)
    dispatch({
      type: GET_CHANNELS,
      payload: res.data,
    });
  })
  .catch((err) => console.log(err));
};

And bellow is my reducer

   import { GET_CHANNELS } from '../actions/types.js';


const initialState = {
  channels: ['channel 1'],
}


export default function (state = initialState,action) {
  switch(action.type) {

    case GET_CHANNELS:
      return {
        ...state,
        channels: action.payload
  };
    default:
      return state;

  }
}

Thank you so much for helping me... I have been following this tutorial https://www.youtube.com/watch?v=BmL8iaLMnQ0&list=PLillGF-RfqbbRA-CIUxlxkUpbq0IFkX60&index=4&ab_channel=TraversyMedia, and I can't identify where I am making a mistake.


Solution

  • You need to call the method, so do this.props.getChannels() instead of this.props.getChannels

    But generally, you should be using the useSelector and useDispatch hooks in 2022. connect/mapStateToProps are a legacy api that is only around to provide support for legacy class components. If you are following a tutorial sthat shows you connect, it probably also shows you other outdated concepts: modern Redux does not use switch..case reducers, ACTION_TYPEs, hand-written action creators, immutable reducer logic or createStore and applyMiddleware. As a consequence, modern Redux is less prone to bugs, easier to read and only 1/4 of the code. If your tutorial is still showing these outdated practices, please follow the official Redux tutorial instead.