N
N
Ninja Mate2017-07-04 20:34:20
JavaScript
Ninja Mate, 2017-07-04 20:34:20

How to make onChange function through redux?

Need to do an action (Universal function for input onChange ) in redux that takes two values

onChange={e=>this.props.loginActions.onChangeUser(e.target.value, e.target.name)}

here is my login component

import React, {Component} from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import TextFieldGroup from '../common/TextFieldGroup';

import * as authActions from '../../actions/authActions'

class LoginForm extends Component {
...
  render() {
    return (
      <form onSubmit={()=>this.onSubmit}>
        <h1>Login</h1>

        <TextFieldGroup
          field="username"
          label="Username"
          value={this.props.username}
          onChange={e=>this.props.loginActions.onChangeUser(e.target.value, e.target.name)}
        />
\
        <div className="form-group"><button className="btn btn-primary btn-lg" disabled={this.props.login.isLoading}>Login</button></div>
      </form>
    );
  }
}

LoginForm.propTypes = {
  login: PropTypes.object.isRequired
}

export const mapStateToProps = state => {
    return {
        login: state.login
    }
}

const mapDispatchToProps = dispatch => ({
    loginActions: bindActionCreators(authActions, dispatch)
})

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(LoginForm)

Actions
import * as login from '../types/login';
//как сделать правильно? 
export function onChangeUser(value, name) {
  return {
    type:     login.ON_CHANGE_USER,
    [name]: value
  };
}

reducer
import  * as loginActions  from '../types/login'

const initialState = {
...
    username: '',
}

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

        case loginActions.ON_CHANGE_USER:
            return {
                //что здесь и как возвращать?
            }

    default:
        return state
  }
}

In types I simply declare const export const ON_CHANGE_USER = 'ON_CHANGE_USER';
How can I do this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2017-07-04
@victorzadorozhnyy

export function onChangeUser(value, name) {
  return {
    type:     login.ON_CHANGE_USER,
    fieldName: name,
    value: value
  };
}
...
case loginActions.ON_CHANGE_USER:
  return {
    ...state,
    [action.fieldName]: action.value
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question