Search code examples
reactjsreact-reduxredux-thunk

React Redux action payload data undefined


I'm trying to set up authentication for my app. Data is returned by axios and action payload is called correctly. The problem comes when I try to access the data contained in the payload. It returns undefined.

Sign in component with redux-form:

class Signin extends Component {
  submit = values => {
    this.props.signInAction(values, this.props.history);
  };

  errorMessage() {
    if (this.props.errorMessage) {
      return <div className="info-red">{this.props.errorMessage}</div>;
    }
  }

  render() {
    const { handleSubmit } = this.props;
    return (
      <form onSubmit={handleSubmit(this.submit)} className="formu">
        <div>
          <div className="inputf">
            <Field
              name="login"
              component="input"
              type="text"
              placeholder="Username"
            />
          </div>
        </div>
        <div>
          <div className="inputf">
            <Field
              name="password"
              component="input"
              type="password"
              placeholder="Password"
            />
          </div>
        </div>
        <div>
          <button className="bsignin" type="submit">
            Sign in
          </button>
          {this.errorMessage()}
        </div>
      </form>
    );
  }
}

function mapStateToProps(state) {
  return { errorMessage: state.auth.error };
}

const reduxFormSignin = reduxForm({
  form: "signin"
})(Signin);

export default connect(
  mapStateToProps,
  { signInAction }
)(reduxFormSignin);

Action creator

export function signInAction({ login, password }, history) {
  return async dispatch => {
    try {
      const res = await HTTP.post(`authenticate`, {
        login,
        password
      });
      localStorage.setItem("token", res.data.token);
      const req = await HTTP.get("account");
      dispatch({
        type: AUTHENTICATED,
        payload: req.data
      });
      history.push("/");
    } catch (error) {
      dispatch({
        type: AUTHENTICATION_ERROR,
        payload: "Invalid userName or password"
      });
    }
  };
}

Reducer

import {
  AUTHENTICATED,
  UNAUTHENTICATED,
  AUTHENTICATION_ERROR
} from "../actions";

const initialState = {
  login: "",
  authority: ""
};

export default function(state = initialState, action) {
  switch (action.type) {
    case AUTHENTICATED:
      //This console log works and returns the data
      console.log(action.payload);
      //Next console log returns payload is undefined
      //console.log(action.payload.login);
      return {
        ...state,
        authenticated: true,
        // login: action.payload.login,
        // authority: action.payload.authority
      };
    case UNAUTHENTICATED:
      return { ...state, authenticated: false };
    case AUTHENTICATION_ERROR:
      return { ...state, error: action.payload };
    default:
      return state;
  }
}

I'd like to set login and authority with the data comming from the payload but can't access the data inside it. ¿What am I missing?


Solution

  • Redux Form has an onSubmit function which takes in an action directly https://redux-form.com/8.1.0/examples/remotesubmit/

    <form onSubmit={handleSubmit} className="formu">
    

    Then wrap within Redux Form

      const reduxFormSignin = reduxForm({
      form: "signin",
      onSubmit: signInAction
    })(Signin);
    
    

    Check within the Redux Debugger, you should see redux form recording data Also remember to pass form reducer to your store as stated here https://redux-form.com/8.1.0/docs/gettingstarted.md/

    import { createStore, combineReducers } from 'redux'
    import { reducer as formReducer } from 'redux-form'
    
    const rootReducer = combineReducers({
      // ...your other reducers here
      // you have to pass formReducer under 'form' key,
      // for custom keys look up the docs for 'getFormState'
      form: formReducer`enter code here`
    })