robert
robert

Reputation: 51

the reducer is not performed

I just tried make simply reducer in react redux but it never called. After a lot trial i have no idea why it's not working. console.log in action is showing but reducer never is called.

import React from "react";
import { connect } from "react-redux";
import * as actions from "store/actions";

function Login(props) {

const login = (e) => {
e.preventDefault();
props.login();
};

return (
  <form onSubmit={login}>
    <button> login </button> 
  </form>
);
}

const mapDispatchToProps = (dispatch) => {
  return {
   login: () => dispatch(actions.login),
  };
};

export default connect(null, mapDispatchToProps)(Login);

actions file- i'm here console.log is showing correctly

import * as actionsTypes from "./actionTypes";

export const logout = () => {
return {
  type: actionsTypes.AUTH_LOGOUT,
 };
};
export const login = () => {
 console.log("i'm here")
 return {
  type: actionsTypes.AUTH_LOGIN,
 };
};

reducer

import * as actionTypes from "../actions/actionTypes";

const initialState = {
  isLogged: false,
};

const reducer = (state = initialState, action) => {
switch (action.type) {
  case actionTypes.AUTH_LOGIN:
    return {
     ...state,
     isLogged: true,
  };
case actionTypes.AUTH_LOGOUT:
  return {
    ...state,
    isLogged: false,
  };
default:
  return state;
 }
};

export default reducer;

many thanks for help

Upvotes: 0

Views: 52

Answers (1)

Skyrocker
Skyrocker

Reputation: 1049

Probably, you forget to make a configuration of the store itself? :)

Something like that:

// at configureStore.js

import { createStore } from 'redux';
import reducer from '../path/to/your/root/reducer'; // assuming that you use combineReducer function to gather all reducers in one place 

export default createStore(reducer);

Then in your app root you need to wrap entry component with the store provider:

import store from './store/configureStore';
import { Provider } from 'react-redux';

export default () => (
  <Provider store={store}>
    <AppRootComponent />
  </Provider>
);

AppRootComponent -> your initial app component


For reference - how to configure store


UPD: Looks like you were trying to pass the action creator to the dispatch function, instead of invoking it actually. Just make a call of that creator in the dispatch:

login: () => dispatch(actions.login()),

BTW, here is the working example of your case

Upvotes: 1

Related Questions