Pass initial value to redux-form - javascript

I want to pass initial values (coming from the props of a react-redux component) to my redux-form. But, I get not value when I inspect the data passed to the renderField . I followed the posts here in SO and on redux-form git forum, and I'm using initialValues in mapStateToProps but still it doesn't work.
This is my react-redux component which holds the redux-form:
class ShowGroup extends Component {
render() {
if (this.state.loading) {
return <div>Loading group ....</div>;
}
if (this.state.error) {
return <div>{this.state.error}</div>;
}
let group = this.props.groups[this.groupId];
return (
<div className="show-group">
<form>
<Field
name="name"
fieldType="input"
type="text"
component={renderField}
label="Name"
validate={validateName}
/>
</form>
</div>
);
}
}
function mapStateToProps(state) {
return {
groups: state.groups,
initialValues: {
name: 'hello'
}
};
}
const mapDispatchToProps = (dispatch) => {
return {
//.....
};
};
export default reduxForm({
form:'ShowGroup'
})(
connect(mapStateToProps, mapDispatchToProps)(ShowGroup)
);
This is my renderField code:
export const renderField = function({ input, fieldType, label, type, meta: { touched, error }}) {
let FieldType = fieldType;
return (
<div>
<label>{label}</label>
<div>
<FieldType {...input} type={type} />
{touched && error && <span>{error}</span>}
</div>
</div>
);
}

You are exporting the wrapped component with incorrect order
export default reduxForm({
form:'ShowGroup'
})(
connect(mapStateToProps, mapDispatchToProps)(ShowGroup)
);
should be
export default connect(mapStateToProps, mapDispatchToProps)(reduxForm({
form:'ShowGroup'
})(ShowGroup);
The reason being that the redux form HOC needs the initialValues prop for itself, if you reverse the order, reduxForm doesn't get the props rather they are passed directly to the component, which doesn't know what to do with it.

Related

React on Rails: Can't enter text in my form input boxes

When I try to type in the boxes on the webpage it doesn't register that I am typing anything. I am guessing it has something to do with the handleChange or onChange, but I could use some help here. I am still pretty new to React and trying to figure it out. What am I missing here?
import React, {Component} from 'react';
import { Form } from 'semantic-ui-react';
class Assessments extends Component {
state = {assessment_name: '', assessment_type: ''}
componentDidMount() {
if (this.props.id) {
const { assessment_name, assessment_type } = this.props
this.setState({ assessment_name, assessment_type })
}
}
handleChange = (a) => {
const { name, value } = a.target
this.setState({ [name]: value })
}
handleSubmit = (a) => {
a.preventDefault()
if (this.props.id) {
const { id, history } = this.props
this.props.updateName(id, this.state, history)
this.props.toggleUpdate()
}
this.props.close()
this.setState({ assessment_name: '', assessment_type: ''})
}
close = () => this.setState({ open: false })
render() {
const { assessment_name, assessment_type } = this.state
return(
<Form onSubmit={this.handleSubmit}>
<Form.Input
name=''
value={assessment_name}
onChange={this.handleChange}
label='Assessment Name'
required
/>
<Form.Input
name='AssessmentType'
value={assessment_type}
onChange={this.handleChange}
label='Assessment Type'
required
/>
<Form.Button>Submit</Form.Button>
</Form>
)
}
}
export default Assessments;
You're not passing the right names to the Form.Input components which the handleChange function uses to update the state. They have to be 'assessment_name' and 'assessment_type' respectively to make sure the state gets updated on input change events and the new values get reflected on the fields.
<>
<Form.Input
name="assessment_name"
value={assessment_name}
onChange={this.handleChange}
label="Assessment Name"
required
/>
<Form.Input
name="assessment_type"
value={assessment_type}
onChange={this.handleChange}
label="Assessment Type"
required
/>
</>

React - Redux-Form Remote Submit

I am attempting to remotely submit a form using redux-forms. My question would be, how do I execute redux actions from a function outside the component. The equivalaent of saying:
this.props.action(params);
My code is as follows:
async function submit(values) {
return (
//Equivalent of => this.props.addOne(values.name)
await actions.addOne(values.name, 60)
)
}
const renderTextField = ({ input, label, meta: { touched, error } }) =>
<TextField
autoFocus
margin="dense"
fullWidth
type="text"
label={label}
{...input}
/>
class LibrarySubsectionForm extends React.Component {
render() {
const { handleSubmit } = this.props;
return (
<form onSubmit={handleSubmit}>
<Field
component={renderTextField}
name="name"
label="Subsection Name"
/>
</form>
)
}
}
export default compose(
connect(null, actions),
reduxForm({ form: 'AddSubsection', onSubmit: submit })
)(LibrarySubsectionForm);
Redux-form is passing dispatch function and props of your decorated component as second and third arguments of onSubmit handler. So basically you have access to them inside your submit function. If you are passing actions as a prop to LibrarySubsectionForm then you can access them inside submit function:
async function submit(values, dispatch, props) {
return await props.actions.addOne(values.name, 60);
}

Redux Form refuses to update

it seems that i am unable to get the form to rerender on each keystroke. I must be doing something wrong I just cannot tell what it is. The GetStartedForm function never runs twice, and neither does the function that contains the Field input.
use of redux form
const GetStartedForm = (props) => {
const {
handleSubmit,
pristine
} = props;
return (
<Form onSubmit={handleSubmit}>
<Field
name="email"
component={FormField}
type="text"
size="xl"
placeholder="Email Address"
autoComplete="email"
validate={[required(), email()]}
/>
<Button
disabled={pristine}>Get Started</Button>
</Form>
);
}
export default reduxForm({ form: 'getstarted' })(GetStartedForm);
implementation
<GetStarted onSubmit={e => {
console.log(e);
}} />
input field
const TextField = props => {
const { input, meta, size } = props;
console.log(props);
const properties = meta.uncontrolled ? {
defaultValue: props.defaultValue
} : {
value: input.value
};
return (
<React.Fragment>
{props.label && (
<label htmlFor={input.name} className="form__label">
{props.label}
{props.required ? ' *' : null}
</label>
)}
<Input
type={props.type ? props.type : 'text'}
className={props.className}
name={input.name}
id={input.name}
size={props.size}
readOnly={props.readOnly}
onChange={input.onChange}
autoFocus={props.autoFocus}
autoComplete={props.autoComplete}
placeholder={props.placeholder}
{...properties}
/>
{meta.touched && meta.error ? (
<div className="form__field-error">{meta.error}</div>
) : null}
</React.Fragment>
);
};
when i pass in uncontrolled like this i am able to get the text to at least show up on my screen, but i seem to be unable to get the form function to run again, which means that my button is stuck at disabled (pristine)
<Field
name="email"
component={FormField}
type="text"
size="xl"
placeholder="Email Address"
autoComplete="email"
validate={[required(), email()]}
meta={{uncontrolled: true}}
/>
yes reducers are set up
/**
* Combine all reducers in this file and export the combined reducers.
*/
import { fromJS } from 'immutable';
import { combineReducers } from 'redux-immutable';
import { LOCATION_CHANGE } from 'react-router-redux';
import { reducer as formReducer } from 'redux-form';
import {
LOGOUT_USER_REQUEST
} from 'constants'
import globalReducer from 'containers/App/reducer';
import languageProviderReducer from 'containers/LanguageProvider/reducer';
/*
* routeReducer
*
* The reducer merges route location changes into our immutable state.
* The change is necessitated by moving to react-router-redux#5
*
*/
// Initial routing state
const routeInitialState = fromJS({
location: null,
});
/**
* Merge route into the global application state
*/
function routeReducer(state = routeInitialState, action) {
switch (action.type) {
/* istanbul ignore next */
case LOCATION_CHANGE:
return state.merge({
location: action.payload,
});
default:
return state;
}
}
/**
* Creates the main reducer with the dynamically injected ones
*/
export default function createReducer(injectedReducers) {
const composite = combineReducers({
route: routeReducer,
global: globalReducer,
language: languageProviderReducer,
form: formReducer,
...injectedReducers,
});
return rootReducer;
function rootReducer(state_, action) {
let state = state_;
if (action.type === LOGOUT_USER_REQUEST) {
state = null;
}
return composite(state, action);
}
}
I just realized that this react boilerplate uses immutable as its base so i had to import redux-form/immutable everywhere i was using redux-form

Input value is null React

I'm not sure what the deal is probably something stupid but when my handle email and handle password handlers are hit, I get null values for text that I entered on the form.
LoginContainer
import React, { Component } from 'react'
import * as AsyncActions from '../actions/User/UserAsyncActions'
import Login from '../components/Login/Login'
class LoginContainer extends Component {
constructor(props) {
super(props)
this.state = {
email: '',
password: ''
}
this.emailIsValid = this.emailIsValid.bind(this)
this.handleEmailInput = this.handleEmailInput.bind(this)
this.handlePasswordInput = this.handlePasswordInput.bind(this)
this.handleLoginPressed = this.handleLoginPressed.bind(this)
}
handlePasswordInput(e, password) {
e.persist()
this.setState(password )
}
handleEmailInput(e, email) {
e.persist()
this.setState(email)
}
handleLoginPressed(e) {
e.persist()
// e.preventDefault()
if (this.emailIsValid(this.state.email) &&
this.passwordIsValid(this.state.password)) {
this.props.login(this.state.email, this.state.password)
}
}
emailIsValid(e, email) {
e.persist()
if (!email) {
return false
}
return true
}
passwordIsValid(e, password) {
e.persist()
if (!password) {
return false
}
return true
}
render(){
return( <Login
handleEmailInput={this.handleEmailInput}
handlePasswordInput={this.handlePasswordInput}
login={this.handleLoginPressed}
/> )
}
}
const mapStateToProps = state => {
return {
requesting: state.user.requesting,
loggedIn: state.user.loggedIn,
token: state.user.token,
session: state.user.session
}
}
export const mapDispatchToProps = {
login: AsyncActions.login
}
export { Login }
export default connect(mapStateToProps, mapDispatchToProps)(LoginContainer)
Login
class Login extends Component {
render(){
return (
<div>
<LoginForm
handleEmailInput={this.props.handleEmailInput}
handlePasswordInput={this.props.handlePasswordInput}
login={this.props.login}
/>
</div>
)
}
}
export default Login
LoginForm
import React, { Component } from 'react'
import { Button, FormControl, FormGroup, ControlLabel, PageHeader } from 'react-bootstrap'
class LoginForm extends Component {
render(){
return (
<div className='ft-login-form'>
<PageHeader className='ft-header'>Login</PageHeader>
<form onSubmit={this.props.login}>
<FormGroup controlId="formBasicText" >
<ControlLabel>Email</ControlLabel>
<FormControl
bsSize="small"
className="ft-username"
componentClass="input"
onChange={this.props.handleEmailInput}
placeholder="Enter mail"
style={{ width: 300}}
type="text"
// value={this.state.email}
/>
<ControlLabel>Password</ControlLabel>
<FormControl
bsSize="small"
className="ft-password"
componentClass="input"
onChange={this.props.handlePasswordInput}
placeholder="Enter Password"
style={{ width: 300}}
type="text"
// value={this.state.password}
/>
</FormGroup>
<Button
className='ft-login-button'
type='submit'>Login</Button>
</form>
</div>)
}
}
export default LoginForm
It looks like you were on the right path with the value={this.state.password}. But since your state is in the parent component, you have to pass the state down and the value becomes value={this.props.value}. The event handlers usually look something like this:
handlePasswordInput(e, password) {
e.persist()
this.setState({ password: e.target.value })
}
They could be different due to the FormControl component but it's worth changing them to see if that's your problem. Also, onChange handlers implicitly pass in e and you have to use a arrow function expression to explicitly pass in anything else.
Edit: If they were able to do something like you mentioned in the comment, they probably did something like this:
handlePasswordInput(e, password) {
e.persist()
const password = e.target.value
this.setState({ password })
}
In es6, { password } is the same as { password: password}

How to render a form with Users information ( React + Redux )

I've managed to get the users information using axios request. I've also managed to render users info on a view using a component that i created. My problem is that i cant display it on an another component i have created which is called ProfileForm. ProfileForm is used as form for updating the info of the user. I want to set the state on the constractor with the user info.
Also, when i change the values to this.props.user.username etc.. i receive two errors:
Warning: Failed prop type: The prop value is marked as required in
TextFieldGroup, but its value is undefined.
in TextFieldGroup (at ProfileForm.js:112)
in ProfileForm (at ProfilePage.js:23)
and the second is
warning.js:36 Warning: TextFieldGroup is changing an uncontrolled
input of type text to be controlled. Input elements should not switch
from uncontrolled to controlled (or vice versa). Decide between using
a controlled or uncontrolled input element for the lifetime of the
component.
class ProfileForm extends React.Component
constructor(props) {
super(props);
this.state = {
username: '',
email: '',
password: '',
passwordConfirmation: '',
errors: {},
isLoading: false,
invalid: false
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({ [event.target.name]: event.target.value });
}
render() {
const { errors } = this.state;
return (
<form onSubmit={this.handleSubmit}>
<TextFieldGroup
error={errors.username}
placeholder="Username"
onChange={this.handleChange}
value={user.username} <-- Here should be the bind
field="username"
/>
<TextFieldGroup
error={errors.email}
placeholder="Email"
onChange={this.handleChange}
checkUserExists={this.checkUserExists}
value={user.email} <-- Here should be the bind
field="email"
/>
<TextFieldGroup
error={errors.password}
placeholder="Password"
onChange={this.handleChange}
value={user.password} <-- Here should be the bind
field="password"
/>
<div className="form-group">
<button disabled={this.state.isLoading || this.state.invalid} className="btn btn-primary btn-md btn-block">Update</button>
</div>
</form>
);
}
}
export default ProfileForm;
Here is my ProfilePage
class ProfilePage extends React.Component {
componentDidMount() {
this.props.getUser();
}
render() {
const { profileUpdateRequest, addFlashMessage, getUser, isUserExists } = this.props;
return (
<div className="row">
<div className="row text-center">
<UserProfile user={this.props.user} /> <-- This works!!!!
</div>
<ProfileForm
profileUpdateRequest={profileUpdateRequest}
addFlashMessage={addFlashMessage}
getUser={getUser}
user={this.props.user} <--- This doesnt work!!!!
isUserExists={isUserExists}
/>
</div>
);
}
}
and my UserProfile which works
export default function UserProfile({ user }) {
const userProfile = (
<div className="row">
{user.username} {user.email}
</div>
);
return (
<div>
{userProfile}
</div>
);
}
My ProfileUpdateAction action
export function getUser() {
return dispatch => {
return axios.get('/api/user')
.then(res => res.data)
.then(data => dispatch(setUser(data.user)));
}
}
And my reducer
import { SET_USER } from '../actions/profileUpdateActions';
export default function user(state = [], action = {}) {
switch(action.type) {
case SET_USER:
return action.user;
default: return state;
}
}
My textFieldGroup
const TextFieldGroup = ({ field, value, label, error, type, onChange, placeholder, min, checkUserExists, disabled }) => {
return (
<div className={classnames("form-group", {'has-error': error})}>
<label className="control-label">{label}</label>
<input
type={type}
name={field}
className="form-control"
value={value}
min={min}
onChange={onChange}
onBlur={checkUserExists}
placeholder={placeholder}
disabled={disabled}
/>
{error && <span className="help-block">{error}</span>}
</div>
);
}
TextFieldGroup.propTypes = {
field: React.PropTypes.string.isRequired,
value: React.PropTypes.string.isRequired,
label: React.PropTypes.string,
error: React.PropTypes.string,
min: React.PropTypes.string,
disabled: React.PropTypes.bool,
placeholder: React.PropTypes.string.isRequired,
type: React.PropTypes.string.isRequired,
onChange: React.PropTypes.func.isRequired,
checkUserExists: React.PropTypes.func
}
TextFieldGroup.defaultProps = {
type: 'text'
}
export default TextFieldGroup;
In UserProfile, you're using a stateless component that is passed in props as an argument. In the function params, you destructure user to be its own constant. Thats cool and works well.
However, in UserForm, you have a class-based component. The props object is attached to the object's context (this). So to access it, you need to use this.props.user.

Categories

Resources