javascriptreactjsreduxredux-actions

Create Action with payload


I'm writing a ReactJS app with redux and redux-actions. I would like to create an redux-action with the login details int the payload as follow:

{
   type: 'AUTH_REQUEST',
   payload: { login: 'Foo', password: 'bar' },
}

...but all of my attempt were not successful.

According to the documentation there should be a way to add a data in the payload, but I'm not proficient enough in frontend stack to really understand.

Here is what I have so far:

action.js

import { createAction } from 'redux-actions';

export const AUTH_REQUEST = 'AUTH_REQUEST'

export const authRequest = createAction(AUTH_REQUEST);

loginFormContainer.js

const mapStateToProps = state => ({
    isLoggedIn: state.authentication.isLoggedIn
})

const mapDispatchToProps = dispatch => ({
    authRequest: () => dispatch(authRequest())
})

export const LoginFormContainer = connect(
    mapStateToProps,
    mapDispatchToProps
)(LoginForm)

loginForm.js

  constructor(props) {
    super(props);
    this.state = {
      email: '',
      password: '',
      errors: {email: '', password: ''},
      emailValid: false,
      passwordValid: false,
      formValid: false
    };
    this.handleEmailChange = this.handleEmailChange.bind(this);
    this.handlePasswordChange = this.handlePasswordChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

 handleSubmit(event) {
    event.preventDefault();
    this.props.authRequest();
  }

I believe that I should be able to give the email and password stored in the state of the loginForm when I handle the submit, but i don't know how to do this... (Yes, I'm new to js). Can anyone give me an hand on that please?


Solution

  • action.js

    const authRequest = createAction(AUTH_REQUEST, (login, password) => ({ login, password }));
    

    loginFormContainer.js

    const mapDispatchToProps = dispatch => ({
        authRequest: (...args) => dispatch(authRequest(...args))
    })
    

    loginForm.js

    handleSubmit(event) {
        event.preventDefault();
        const { email, password } = this.state;
        this.props.authRequest(email, password);
    }