Search code examples
reduxreact-reduxredux-thunk

TypeError: dispatch is not a function when clicking the toggle button


I am using react redux-thunk. I have a set of users data that I get from an API and this is the schema:

enter image description here.

I've connected the "active" property with the checked attribute of a Switch MUI button, so naturally when calling the API I have some users with their switch button already on "true". What I am trying to do is to just make the switch functional, and just be able to click it and change its state, not necessarily doing anything with that.

Here's my toggleType.js:

export const TOGGLE = "TOGGLE";

Here's my toggleAction.js:

import { TOGGLE } from "./toggleType";

const statusToggleAction = () => {
  return {
    type: TOGGLE,
  };
};
export const statusToggle = () => {
  return (dispatch) => {
    dispatch(statusToggleAction);
  };
};

Here's my toggleReducer.js:

import { TOGGLE } from "./toggleType";

const initialState = {
  status: false,
};

const toggleReducer = (state = initialState, action) => {
  switch (action.type) {
    case TOGGLE:
      status: true;
    default:
      return state;
  }
};
export default toggleReducer;

Everything is under my userContainer.js, like that:

function UserContainer({ userData, fetchUsers }) {
  useEffect(() => {
    fetchUsers();
  }, []);
  return userData.loading ? (
    <h2>Loading</h2>
  ) : userData.error ? (
    <h2>{userData.error}</h2>
  ) : (
    <Container maxWidth="lg" style={{ flexGrow: 1, height: "100%" }}>
      <h2>User List</h2>
      <div>
        {userData &&
          userData.users &&
          userData.users.map((user) => (
            <div key={user.id}>
              <p>{user.name}</p>
              <Switch checked={user.active} onChange={statusToggle()} />
            </div>
          ))}
      </div>
    </Container>
  );
}

const mapStateToProps = (state) => {
  return { userData: state.user, statusToggle: state.status };
};
const mapDispatchToProps = (dispatch) => {
  return {
    fetchUsers: () => dispatch(fetchUsers()),
    statusToggle: () => dispatch(statusToggle()),
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(UserContainer);

This is the error I am getting whenever I am clicking one of those switches: enter image description here

Any ideas are welcome, I "learned" redux like 3 days ago!


Solution

  • toggleReducer function in toggleReducer.js, replace status: true; with return { status: true }.

    • Just return action in statusToggle function in toggleAction.js without dispatch as following.
    export const statusToggle = () => {
      return statusToggleAction();
    };
    
    • Or just call statusToggleAction directly in userContainer.js as following.
    export const statusToggle = () => {
      return (dispatch) => {
        dispatch(statusToggleAction());
      };
    };