I am trying to pre-populate Personal Info however I am running into an async issue. Any help will be appreciated.
looked at : https://medium.com/#1sherlynn/react-redux-form-two-ways-to-add-initial-values-ab48daa0a32e and https://redux-form.com/6.0.0-alpha.4/examples/initializefromstate/
class AccountOverview extends Component {
constructor() {
super();
this.state = { data: [] };
}
async componentDidMount() {
const data = { fullname: "fullname", username: "username" }
this.setState({ data })
}
render() {
console.log(this.state.data)
<PersonalInfo
initialValues={this.state.data} />
....
I expect the form to be populated by the data state. I logged with he the following result
[]
{ fullname: "fullname", username: "username" }
i feel the component does not reload after the async call is completed.
PersonalInfo.js:
const PersonalInfo = props => {
const { username, fullname, handleOnChange, validationErrors } = props;
return (
<div>
<h1> Personal Information</h1>
<br />
<Field
type="text"
name="fullname"
icon=""
label="Fullname"
value={fullname}
component={FormField}
onChange={handleOnChange}
/>
<Field
type="text"
name="username"
icon=""
label="Username"
value={username}
component={FormField}
onChange={handleOnChange}
/>
</div>
)
}
function mapStateToProps(state) {
return {
state
};
}
export default reduxForm({form: "AccountOverview"})(connect(mapStateToProps)(PersonalInfo))
From the docs, you have missed important step.
Add initialValuesprop in mapStateToProps and you can retrieve initialValues from the redux store
So your mapStateToProps should be,
const mapStateToProps = (state, props) => ({
initialValues: state, // retrieve data from redux store
})
To pass the initialValues props into the redux form, we use the connect function
Add enableReinitialize : true When set to true, the form will reinitialize every time the initialValues prop changes
This,
export default reduxForm({form: "AccountOverview"})(connect(mapStateToProps)(PersonalInfo))
Should be,
export default connect(
mapStateToProps
)(reduxForm({
form: 'AccountOverview', // a unique identifier for this form
enableReinitialize: true
})(PersonalInfo))
Related
I am building a React form in the CRM pane of Flex which will POST data to an external service when the agent fills out the form and hits a submit button. Using the example code from create-flex-plugin from Plugin Builder v3, I have successfully persisted the data from a form field in redux. However, as an agent in Flex, if I have multiple reservations open, when I toggle between them they use the same data. How do I design my form so that an agent can enter data in the form for different reservations and they are kept separately?
I am relatively new to Flex, React and Redux, and not sure if there is anything Flex-specific about what I need to do, especially when handling multiple concurrent reservations. I've thought of keeping a Map keyed by reservationId or taskId in redux, but it's not clear how I'd pass the taskId into the reducer. I am also not sure if other tools like redux-form will play nice with Flex's design.
Being pointed in the right direction or getting some sample code would be a great help.
My current implementation, which persists a field called 'subcategory', looks like this:
HrmFormState.js
const UPDATE_FORM = 'UPDATE_FORM';
const initialState = {
subcategory: 'my category',
};
export class Actions {
static updateForm = (e) => ({ type: UPDATE_FORM, text: e.target.value });
}
export function reduce(state = initialState, action) {
switch (action.type) {
case UPDATE_FORM: {
return {
...state,
subcategory: action.text,
};
}
default:
return state;
}
}
HrmForm.Container.js
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Actions } from '../../states/HrmFormState';
import HrmForm from './HrmForm';
const mapStateToProps = (state) => ({
subcategory: state['hrm-form'].hrmForm.subcategory,
});
const mapDispatchToProps = (dispatch) => ({
updateForm: bindActionCreators(Actions.updateForm, dispatch),
});
export default connect(mapStateToProps, mapDispatchToProps)(HrmForm);
HrmForm.jsx (snippet)
render() {
if (!this.props.task) {
return null;
}
return (
<HrmFormComponentStyles>
<form onSubmit={this.handleSubmit}>
<label>
Subcategory:
<input type="text" value={this.props.subcategory}
onChange={this.props.updateForm} />
</label>
<input type="submit" value="Submit" />
</form>
</HrmFormComponentStyles>
);
}
I have written code, which uses a Modal dialog to display a form.
My react app is rendered at "root"
index.html
<div id="root"></div>
App.js
const store = configureStore();
ReactDOM.render(
<Provider store={store}>
<ExampleBasic/>
</Provider>
, document.getElementById('root'));
ExmpleBasic.js
Please ignore state management in component here. this is just for example.
import React, { PureComponent } from 'react';
import Lorem from 'react-lorem-component';
import Modal from '#atlaskit/modal-dialog';
import Button from '#atlaskit/button';
export default class ExampleBasic extends PureComponent {
state = { isOpen: false }
open = () => this.setState({ isOpen: true })
close = () => this.setState({ isOpen: false })
secondaryAction = ({ target }) => console.log(target.innerText)
render() {
const { isOpen } = this.state;
const actions = [
{ text: 'Close', onClick: this.close },
{ text: 'Secondary Action', onClick: this.secondaryAction },
];
return (
<div>
<Button onClick={this.open}>Open Modal</Button>
{isOpen && (
<Modal
actions={actions}
onClose={this.close}
heading="Modal Title"
>
<BasicFormContainer />
</Modal>
)}
</div>
);
}
}
BasicFormContainer.js
const mapStateToProps = state => ({
addDesignation: state.designations.addDesignation,
});
const mapDispatchToProps = dispatch => ({
});
export default connect(mapStateToProps, mapDispatchToProps)(BasicForm);
BasicForm.js
import React, { Component } from 'react';
import { Field, reduxForm } from 'redux-form';
class BasicForm extends Component {
constructor(props) {
super(props);
this.submit = this.submit.bind(this);
}
submit(values) {
console.log(values);
}
render() {
const { handleSubmit } = this.props;
return (
<form onSubmit={handleSubmit(this.submit)}>
<Field
name="designationName"
component="input"
placeholder="Name"
label="Enter name"
autoFocus
/>
</form>
);
}
}
export default reduxForm({
form: 'BasicForm',
enableReinitialize: true,
})(BasicForm);
However modal is rendered using portal, outside current DOM.
As modal is rendered outside the scope of redux context, it is not getting the
store. and i am getting an error "Uncaught Error: Field must be inside a component decorated with reduxForm()"
Below is link to same kind of problem, where redux form within portal is not working.
Redux Form Wrapped Inside Custom Portal Component?
in React 16 it is handled by portals, but version before then that you can try something like as follow.
export default class ExampleBasic extends PureComponent {
...
static contextTypes = { store: React.PropTypes.object };
render() {
const { isOpen } = this.state;
const actions = [
{ text: 'Close', onClick: this.close },
{ text: 'Secondary Action', onClick: this.secondaryAction },
];
return (
<div>
<Button onClick={this.open}>Open Modal</Button>
{isOpen && (
<Modal
actions={actions}
onClose={this.close}
heading="Modal Title"
>
<Provider store={this.context.store}>
<BasicFormContainer />
</Provider>
</Modal>
)}
</div>
);
}
}
You need to pass in the values of BasicForm.js to the Redux store and dispatch an action from there itself and not from the BasicFormContainer.js. This way, the Modal remains inside of the scope of your root element and thus there is no need to access the store outside of the Provider.
Then update the Redux store based on the values entered in the form. Once, the store is updated, you can then access it from anywhere in your application such as Modal in your case.
I downgraded to version 2.1.0 to solve the problem.
I am fetching data from a remote API in componentDidMount:
componentDidMount() {
this.props.fetchRemoteData('photos')
}
And then the received data is passed to my component props in mapStateToProps, using a selector to filter a specific object from the received array:
const mapStateToProps = (state, { params }) => {
const photoId = parseInt(params.photoId)
return {
singlePhoto: getSinglePhoto(state.filteredList.photos.jsonArray, photoId),
isFetching: state.filteredList.photos.isFetching
}
}
The content renders, but there is a split second before that, where it seems to be trying to the render the content before the data is successfully retrieved, which brings up the following error in the console:
Uncaught TypeError: Cannot read property 'charAt' of undefined
undefined is here referring to this.props.singlePhoto. But when singlePhoto receives the data payload the content renders.
Here is my container component:
class PhotoSingle extends Component {
componentDidMount() {
this.props.fetchRemoteData('photos')
}
render() {
const {singlePhoto, isFetching} = this.props
const photoTitle = capitalizeFirstLetter(singlePhoto.title)
return (
<div>
<PhotoSingleImg singlePhoto={singlePhoto} photoTitle={photoTitle} isFetching={isFetching}/>
</div>
)
}
}
const mapStateToProps = (state, { params }) => {
const photoId = parseInt(params.photoId)
return {
singlePhoto: getSinglePhoto(state.filteredList.photos.jsonArray, photoId),
isFetching: state.filteredList.photos.isFetching
}
}
import * as actions from '../actions/actionCreators'
PhotoSingle = connect(mapStateToProps, actions)(PhotoSingle)
export default PhotoSingle;
And my presentational component:
const PhotoSingleImg = ({ singlePhoto, photoTitle, isFetching }) => {
if (isFetching) {
return <h4>Fetching data...</h4>
}
return (
<div>
<h1>Single Photo</h1>
<h3>Title</h3>
<hr />
<img className='single-photo' src={singlePhoto.url} />
<p>Album ID: {singlePhoto.albumId} | Photo ID: {singlePhoto.id}</p>
</div>
)
}
export default PhotoSingleImg;
I'm unsure how to make it so the content will only attempt to render after I the API response has been received.
Any help appreciated.
Have you defined initial state in redux store?
You can try this way:
return singlePhoto ?
(<div>
<h1>Single Photo</h1>
<h3>Title</h3>
<hr />
<img className='single-photo' src={singlePhoto.url} />
<p>Album ID: {singlePhoto.albumId} | Photo ID: {singlePhoto.id}</p>
</div>) : null
I have a problem rendering initialValues passed to a form using redux-form/immutable (v6.0.5) with a custom component:
// WRAPPER COMPONENT
import React from 'react';
import {connect} from 'react-redux';
import DocumentsEditForm from './documentsEditForm';
import {documentsGetOneInfo} from './../../../modules/documents/actions/documents_get_one_info';
import {documentsPut} from './../../../modules/documents/actions/documents_put';
#connect((state) => {
return ({
selectedDocument: state.getIn(['documents', 'selectedDocument']).toJS()
});
})
class DocumentsEdit extends React.Component {
static propTypes = {
dispatch: React.PropTypes.func,
isLoading: React.PropTypes.bool,
routing: React.PropTypes.object,
selectedDocument: React.PropTypes.object
};
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
componentWillMount() {
this.props.dispatch(adminDocumentsGetOneInfo(this.props.routing.locationBeforeTransitions.query.id));
}
handleSubmit(data) {
this.props.dispatch(documentsPut(data));
}
render() {
const initialValues = (this.props.selectedDocument.id) ? {
filename: this.props.selectedDocument.filename,
id: this.props.selectedDocument.id
} : {};
return (
<DocumentsEditForm
enableReinitialize
initialValues={initialValues}
onSubmitDocumentsEditForm={this.handleSubmit}
/>
);
}
}
export default DocumentsEdit;
Here is the form component itself:
import React from 'react';
import {Field, reduxForm} from 'redux-form/immutable';
import {Button} from 'react-bootstrap';
import InputTextRedux from './../../shared/components/input_text_redux';
import InputSelectRedux from './../../shared/components/input_select_redux';
let DocumentsEditForm = (props) => {
const {error, handleSubmit, pristine} = props;
return (
<form
onSubmit={handleSubmit(props.onSubmitDocumentsEditForm)}
>
<Field
component={InputTextRedux}
disabled
name="id"
type="text"
/>
<Field
component={InputTextRedux}
name="filename"
type="text"
/>
<Button
type="submit"
>
{'Save'}
</Button>
</form>
);
};
DocumentsEditForm.propTypes = {
error: React.PropTypes.object,
handleSubmit: React.PropTypes.func,
onSubmitDocumentsEditForm: React.PropTypes.func,
pristine: React.PropTypes.bool
};
documentsEditForm = reduxForm({
form: 'documentsEditForm'
})(DocumentsEditForm);
export default DocumentsEditForm;
And here is the custom InputTextRedux component:
import React from 'react';
import {ControlLabel, FormControl, FormGroup, InputGroup} from 'react-bootstrap';
const InputTextRedux = (props) => {
const {
id,
disabled,
input,
type
} = props;
return (
<div>
<FormGroup
name={input.name ? input.name : ''}
>
<ControlLabel>
{'Label'}
</ControlLabel>
<InputGroup>
<FormControl
disabled={disabled ? true : false}
id={id ? id : input.name}
onChange={(event) => {
input.onChange(event.target.value);
}}
type={type ? type : 'text'}
value={input.value ? input.value : ''}
/>
<FormControl.Feedback />
</InputGroup>
</FormGroup>
</div>
);
};
InputTextRedux.propTypes = {
disabled: React.PropTypes.bool,
id: React.PropTypes.string,
input: React.PropTypes.object,
type: React.PropTypes.string,
};
export default InputTextRedux;
I can submit the form and get the correct initialValues passed to handleSubmit but I can't seem to get the values displayed.
According to DevTools redux-form/INITIALIZE gets called with the correct payload and also the state at state->form->documentsEditForm->values/initial is correctly updated.
I also tried loading fixed initialValues to rule out problems with the api call delay but I got the same result. "input: {value: ''}" is always an empty string in the Field props.
What I noticed was that inside the props the form component recieves the structure looks as follows:
props {
....
initialValues: {
__altered: false,
_root: {
entries: [
[
'id',
'123456'
],
[
'filename',
'test.txt'
]
]
},
size: 2
},
....
}
If I try to set a field's value directly to "props.initialValues._root.entries[0][1] for example it works.
Also I noticed since the full form has a Field with name="size" that this value gets filled correctly with the value "2" from initialValues above. So it seems as if the form is looking at the wrong "level" of initialValues for the values. To test this I also tried naming a Field "__altered" and its value was correctly set to false.
What am I doing wrong? Thanks alot!
This has been resolved: See https://github.com/erikras/redux-form/issues/1744#issuecomment-251140419
Basically I had to import "redux-form/immutable" instead of "redux-form".
On the official pages and in the GitHub issues for redux-form there are more than one example of how to work with initialValues however I cannot find a single one that focuses on explaining how initialValues can be set in response to an asynchronous source.
The main case that I have in mind is something like a simple CRUD application where a user is going to edit some entity that already exists. When the view is first opened and the redux-form component is mounted but before the component is rendered the initialValues must be set. Lets say that in this example that the data is loaded on demand when the component is first mounted and rendered for the first time. The examples show setting initialValues based on hard coded values or the redux store state but none that I can find focus on how to set the initialValues based on something async like a call to XHR or fetch.
I'm sure I'm just missing something fundamental so please point me in the right direction.
References:
Initializing Form State
Handling form defaults
What is the correct way to populate a dynamic form with initial data?
EDIT: Updated Solution from ReduxForm docs
This is now documented in the latest version of ReduxForm, and is much simpler than my previous answer.
The key is to connect your form component after decorating it with ReduxForm. Then you will be able to access the initialValues prop just like any other prop on your component.
// Decorate with reduxForm(). It will read the initialValues prop provided by connect()
InitializeFromStateForm = reduxForm({
form: 'initializeFromState'
})(InitializeFromStateForm)
// now set initialValues using data from your store state
InitializeFromStateForm = connect(
state => ({
initialValues: state.account.data
})
)(InitializeFromStateForm)
I accomplished this by using the redux-form reducer plugin method.
The following demos fetching async data and pre-populating a user form with response.
const RECEIVE_USER = 'RECEIVE_USER';
// once you've received data from api dispatch action
const receiveUser = (user) => {
return {
type: RECEIVE_USER,
payload: { user }
}
}
// here is your async request to retrieve user data
const fetchUser = (id) => dispatch => {
return fetch('http://getuser.api')
.then(response => response.json())
.then(json => receiveUser(json));
}
Then in your root reducer where you include your redux-form reducer you would include your reducer plugin that overrides the forms values with the returned fetched data.
const formPluginReducer = {
form: formReducer.plugin({
// this would be the name of the form you're trying to populate
user: (state, action) => {
switch (action.type) {
case RECEIVE_USER:
return {
...state,
values: {
...state.values,
...action.payload.user
}
}
default:
return state;
}
}
})
};
const rootReducer = combineReducers({
...formPluginReducer,
...yourOtherReducers
});
Finally you include you combine your new formReducer with the other reducers in your app.
Note The following assumes that the fetched user object's keys match the names of the fields in the user form. If this is not the case you will need to perform an additional step on the data to map fields.
By default, you may only initialize a form component once via initialValues. There are two methods to reinitialize the form component with new "pristine" values:
Pass a enableReinitialize prop or reduxForm() config parameter set to true to allow the form the reinitialize with new "pristine" values every time the initialValues prop changes. To keep dirty form values when it reinitializes, you can set keepDirtyOnReinitialize to true. By default, reinitializing the form replaces all dirty values with "pristine" values.
Dispatch the INITIALIZE action (using the action creator provided by redux-form).
Referenced from : http://redux-form.com/6.1.1/examples/initializeFromState/
Could you fire the dispatch on componentWillMount(), and set the state to loading.
While it is loading, render a spinner for example and only when the request returns with the values, update the state, and then re-render the form with the values??
Here is minimal working example on how to set initialValues based on async source.
It uses initialize action creator.
All values from initialValues shouldn't be undefined, or you will get an infinite loop.
// import { Field, reduxForm, change, initialize } from 'redux-form';
async someAsyncMethod() {
// fetch data from server
await this.props.getProducts(),
// this allows to get current values of props after promises and benefits code readability
const { products } = this.props;
const initialValues = { productsField: products };
// set values as pristine to be able to detect changes
this.props.dispatch(initialize(
'myForm',
initialValues,
));
}
While this method may not be the best solution, it works well enough for my needs:
AJAX request to API on entry
Initializes form with data when request has been fulfilled or displays a server error
Resetting form will still reset to initial seed data
Allows the form to be reused for other purposes (for example, a simple if statement could bypass setting initial values): Add Post and Edit Post or Add Comment and Edit Comment...etc.
Data is removed from Redux form on exit (no reason to store new data in Redux since it's being re-rendered by a Blog component)
Form.jsx:
import React, { Component } from 'react';
import { Field, reduxForm } from 'redux-form';
import { connect } from 'react-redux';
import { browserHistory, Link } from 'react-router';
import { editPost, fetchPost } from '../../actions/BlogActions.jsx';
import NotFound from '../../components/presentational/notfound/NotFound.jsx';
import RenderAlert from '../../components/presentational/app/RenderAlert.jsx';
import Spinner from '../../components/presentational/loaders/Spinner.jsx';
// form validation checks
const validate = (values) => {
const errors = {}
if (!values.title) {
errors.title = 'Required';
}
if (!values.image) {
errors.image = 'Required';
}
if (!values.description) {
errors.description = 'Required';
} else if (values.description.length > 10000) {
errors.description = 'Error! Must be 10,000 characters or less!';
}
return errors;
}
// renders input fields
const renderInputField = ({ input, label, type, meta: { touched, error } }) => (
<div>
<label>{label}</label>
<div>
<input {...input} className="form-details complete-expand" placeholder={label} type={type}/>
{touched && error && <div className="error-handlers "><i className="fa fa-exclamation-triangle" aria-hidden="true"></i> {error}</div>}
</div>
</div>
)
// renders a text area field
const renderAreaField = ({ textarea, input, label, type, meta: { touched, error } }) => (
<div>
<label>{label}</label>
<div>
<textarea {...input} className="form-details complete-expand" placeholder={label} type={type}/>
{touched && error && <div className="error-handlers"><i className="fa fa-exclamation-triangle" aria-hidden="true"></i> {error}</div>}
</div>
</div>
)
class BlogPostForm extends Component {
constructor() {
super();
this.state = {
isLoaded: false,
requestTimeout: false,
};
}
componentDidMount() {
if (this.props.location.query.postId) {
// sets a 5 second server timeout
this.timeout = setInterval(this.timer.bind(this), 5000);
// AJAX request to API
fetchPost(this.props.location.query.postId).then((res) => {
// if data returned, seed Redux form
if (res.foundPost) this.initializeForm(res.foundPost);
// if data present, set isLoaded to true, otherwise set a server error
this.setState({
isLoaded: (res.foundPost) ? true : false,
serverError: (res.err) ? res.err : ''
});
});
}
}
componentWillUnmount() {
this.clearTimeout();
}
timer() {
this.setState({ requestTimeout: true });
this.clearTimeout();
}
clearTimeout() {
clearInterval(this.timeout);
}
// initialize Redux form from API supplied data
initializeForm(foundPost) {
const initData = {
id: foundPost._id,
title: foundPost.title,
image: foundPost.image,
imgtitle: foundPost.imgtitle,
description: foundPost.description
}
this.props.initialize(initData);
}
// onSubmit => take Redux form props and send back to server
handleFormSubmit(formProps) {
editPost(formProps).then((res) => {
if (res.err) {
this.setState({
serverError: res.err
});
} else {
browserHistory.push(/blog);
}
});
}
renderServerError() {
const { serverError } = this.state;
// if form submission returns a server error, display the error
if (serverError) return <RenderAlert errorMessage={serverError} />
}
render() {
const { handleSubmit, pristine, reset, submitting, fields: { title, image, imgtitle, description } } = this.props;
const { isLoaded, requestTimeout, serverError } = this.state;
// if data hasn't returned from AJAX request, then render a spinner
if (this.props.location.query.postId && !isLoaded) {
// if AJAX request returns an error or request has timed out, show NotFound component
if (serverError || requestTimeout) return <NotFound />
return <Spinner />
}
// if above conditions are met, clear the timeout, otherwise it'll cause the component to re-render on timer's setState function
this.clearTimeout();
return (
<div className="col-sm-12">
<div className="form-container">
<h1>Edit Form</h1>
<hr />
<form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}>
<Field name="title" type="text" component={renderInputField} label="Post Title" />
<Field name="image" type="text" component={renderInputField} label="Image URL" />
<Field name="imgtitle" component={renderInputField} label="Image Description" />
<Field name="description" component={renderAreaField} label="Description" />
<div>
<button type="submit" className="btn btn-primary partial-expand rounded" disabled={submitting}>Submit</button>
<button type="button" className="btn btn-danger partial-expand rounded f-r" disabled={ pristine || submitting } onClick={ reset }>Clear Values</button>
</div>
</form>
{ this.renderServerError() }
</div>
</div>
)
}
}
BlogPostForm = reduxForm({
form: 'BlogPostForm',
validate,
fields: ['name', 'image', 'imgtitle', 'description']
})(BlogPostForm);
export default BlogPostForm = connect(BlogPostForm);
BlogActions.jsx:
import * as app from 'axios';
const ROOT_URL = 'http://localhost:3001';
// submits Redux form data to server
export const editPost = ({ id, title, image, imgtitle, description, navTitle }) => {
return app.put(`${ROOT_URL}/post/edit/${id}?userId=${config.user}`, { id, title, image, imgtitle, description, navTitle }, config)
.then(response => {
return { success: response.data.message }
})
.catch(({ response }) => {
if(response.data.deniedAccess) {
return { err: response.data.deniedAccess }
} else {
return { err: response.data.err }
}
});
}
// fetches a single post from the server for front-end editing
export const fetchPost = (id) => {
return app.get(`${ROOT_URL}/posts/${id}`)
.then(response => {
return { foundPost: response.data.post}
})
.catch(({ response }) => {
return { err: response.data.err };
});
}
RenderAlert.jsx:
import React, { Component } from 'react';
const RenderAlert = (props) => {
const displayMessage = () => {
const { errorMessage } = props;
if (errorMessage) {
return (
<div className="callout-alert">
<p>
<i className="fa fa-exclamation-triangle" aria-hidden="true"/>
<strong>Error! </strong> { errorMessage }
</p>
</div>
);
}
}
return (
<div>
{ displayMessage() }
</div>
);
}
export default RenderAlert;
Reducers.jsx
import { routerReducer as routing } from 'react-router-redux';
import { reducer as formReducer } from 'redux-form';
import { combineReducers } from 'redux';
const rootReducer = combineReducers({
form: formReducer,
routing
});
export default rootReducer;
use this :
UpdateUserForm = reduxForm({
enableReinitialize: true,
destroyOnUnmount: false,
form: 'update_user_form' // a unique identifier for this form
})(UpdateUserForm);
UpdateUserForm = connect(
(state) => ({
initialValues: state.userManagment.userSingle
})
)(UpdateUserForm);
export default UpdateUserForm;