"user.profile" undefined despite its declaration in Accounts.createUser() - javascript

I am working on a "settings" page where a logged in user can change their profile picture. However it seems that Meteor is having trouble finding the profile attribute for a user.
signup.js (here is where I create the user on signup and create the profile attribute)
import React, { Component } from 'react';
import { browserHistory } from 'react-router';
export default class Signup extends Component {
handleSubmit(event) {
event.preventDefault();
var signupEmail = event.target.signupEmail.value;
var signupPassword = event.target.signupPassword.value;
if (signupPassword !== '') {
Accounts.createUser({
email: signupEmail,
password: signupPassword,
profile: {
avatar: "/user-default.svg"
}
}, (err) => {
err ? (console.log(err.reason)) : browserHistory.push("/app/profile");
});
}
}
render() {
return (
<div className="login-form">
<form onSubmit={this.handleSubmit}>
<div className="input-options">
<input type="text" placeholder="Email" name="signupEmail" />
</div>
<div className="input-options">
<input type="password" placeholder="Password" name="signupPassword" />
</div>
<button className="login-submit bold">Sign me up!</button>
</form>
</div>
);
}
}
profile_settings.js
import React, { Component } from 'react';
import { Link } from 'react-router';
import reactMixin from 'react-mixin';
import ReactMeteorData from 'meteor/react-meteor-data';
export default class ProfileSettings extends Component {
constructor(props) {
super(props);
this.state = {
avatar: this.props.user.profile.avatar
}
}
getMeteorData(){
return{
user: Meteor.user()
}
}
componentWillMount(){
// we create this rule both on client and server
Slingshot.fileRestrictions("avatar", {
allowedFileTypes: ["image/png", "image/jpeg", "image/gif"],
maxSize: 2 * 500 * 500
});
}
upload(){
var userId = Meteor.user()._id;
var metaContext = {avatarId: userId};
var uploader = new Slingshot.Upload("UsersAvatar", metaContext);
uploader.send(document.getElementById('input').files[0], function (error, downloadUrl) { // you can use refs if you like
if (error) {
// Log service detailed response
console.error('Error uploading', uploader.xhr.response);
alert (error); // you may want to fancy this up when you're ready instead of a popup.
}
else {
// we use $set because the user can change their avatar so it overwrites the url :)
Meteor.users.update(Meteor.userId(), {$set: {"profile.avatar": downloadUrl}});
}
// you will need this in the event the user hit the update button because it will remove the avatar url
this.setState({avatar: downloadUrl});
}.bind(this));
}
formSubmit(){
let avatarUrl = this.state.avatar;
Meteor.users.update( {_id: Meteor.userId() }, {
$set: {profile: avatarUrl}
});
}
render() {
return (
<div>
<div className="sticky-header">
<h3>Settings</h3>
</div>
<form>
<div className="row well">
<div className="col-md-6">
<div className="form-group">
<label htmlFor="exampleInputFile">File input</label>
<input type="file" id="input" onChange={this.upload.bind(this)} />
<p className="help-block">Image max restriction: 2MB, 500x500. Cropped: 200x200</p>
</div>
</div>
<div className="col-md-6 utar-r">
<img src={this.state.avatar} height="200" width="200" alt="..." className="img-rounded" />
</div>
<div className="form-group">
<button className="btn btn-lg btn-primary btn-block" type="submit" onClick={this.formSubmit.bind(this)}>Update Profile</button>
</div>
</div>
</form>
<footer className="sticky-footer">
<Link to="/app/profile">
<button className="profile-edit bg-black">
<h3>Cancel</h3>
</button>
</Link>
<Link to="">
<button className="profile-edit">
<h3>Save Changes</h3>
</button>
</Link>
</footer>
</div>
);
}
}
reactMixin(ProfileSettings.prototype, ReactMeteorData);
Here is the error I am getting: TypeError: Cannot read property 'profile' of undefined

The error is not failing to find an profile attribute, but says that there's no user (or that user is undefined) This is exactly what TypeError: Cannot read property 'profile' of undefined means.
There are a few errors in your code:
the return of getMeteorData is available under this.data and not this.props
getMeteorData will run after constructor so there's no way to get Meteor's data in the constructor
getMeteorData returns data reactively, and is likely not to have the data you want when you instantiate the class anyway
So I'd recommend using the container/component approach that is like:
export default class ProfileSettingsContainer extends Component {
getMeteorData(){
return{
user: Meteor.user()
}
}
render() {
const user = this.data.user;
if (user) {
return <ProfileSettings user={user} />
} else {
return null; // or what ever placeholder you want while the data is being loaded
}
}
}
class ProfileSettings extends Component {
constructor(props) {
super(props);
this.state = {
avatar: props.user.profile.avatar
}
}
}
with this structure, the ProfileSettings will instantiate with something under props.user
Finnaly,
Meteor.users.update( {_id: Meteor.userId() }, {
$set: {profile: avatarUrl}
});
should be
Meteor.users.update( {_id: Meteor.userId() }, {
$set: {'profile.avatar': avatarUrl}
});
but that's unrelated

Related

REACTJS AND API pass the value of Api to another page

I really need help cause I'm totally new to reactjs. How can I maintain the logged-in user throughout the page? like a session. the code shows the data called when I logged in. I'm really lost here in react.
When the credentials are true, here's the result
{userId: 1, firstname: "Jeff", middlename: null, lastname: "Geli", positionId: 1, …}
userId: 1
firstname: "Jeff"
middlename: null
lastname: "Geli"
positionId: 1
token: "eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTI1NiIsInR5cCI6IkpXVCJ9.eyJMb2dnZWRVc2VyIjoie1wiVXNlcklkXCI6MSxcIkZpcnN0bmFtZVwiOlwiSmVmZlwiLFwiTWlkZGxlbmFtZVwiOm51bGwsXCJMYXN0bmFtZVwiOlwiR2VsaVwiLFwiUG9zaXRpb25JZFwiOjEsXCJUb2tlblwiOm51bGx9IiwiZXhwIjoxNTc5NzU5MzI5LCJpc3MiOiJzbWVzay5pbiIsImF1ZCI6InJlYWRlcnMifQ.xXPW0ijBdULuMBfhFGyL1qF1bA--FzG64jEJVMQZWY8"
__proto__: Object
import React from 'react';
import { Link, withRouter } from 'react-router-dom';
import { PageSettings } from './../../config/page-settings.js';
import bg from '../../assets/login-bg-17.jpg';
import axios from "axios";
class LoginV2 extends React.Component {
static contextType = PageSettings;
constructor(props) {
super(props);
//credentials for login
this.state = {
username: '',
password: '',
};
this.handleSuccess = this.handleSuccess.bind(this);
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
componentDidMount() {
this.context.handleSetPageSidebar(false);
this.context.handleSetPageHeader(false);
}
componentWillUnmount() {
this.context.handleSetPageSidebar(true);
this.context.handleSetPageHeader(true);
}
handleChange(event) {
this.setState({
[event.target.name]: event.target.value
});
};
handleSuccess(data) {
alert("Logged IN");
this.props.history.push('dashboard/v2');
}
//When submit button is clicked, fetch API
async handleSubmit(event) {
event.preventDefault();
//fetch API, method POST
const getCred = await fetch('/api/login', {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'ApiKey': "Secret"
},
method: "POST",
body: JSON.stringify({
username: this.state.username,
password: this.state.password
}),
});
const data = await getCred.json();
if (getCred.status == 400) {
alert(data);
} else {
this.handleSuccess(getCred);
}
console.log(data);
}
render() {
return (
<React.Fragment>
<div className="login-cover">
<div className="login-cover-image" style={{backgroundImage:'url('+ bg +')'}} >
</div>
<div className="login-cover-bg"></div>
</div>
<div className="login login-v2">
<div className="login-header">
<div className="brand">
<span className="logo"></span> <b>Tek</b> Teach
<small>Leraning Management System</small>
</div>
<div className="icon">
<i className="fa fa-lock"></i>
</div>
</div>
<div className="login-content">
<form className="margin-bottom-0" onSubmit={this.handleSubmit}>
<div className="form-group m-b-20">
<input type="text" className="form-control form-control-lg" placeholder="Username" name="username" value={this.state.username} onChange={this.handleChange} required />
</div>
<div className="form-group m-b-20">
<input type="password" className="form-control form-control-lg" placeholder="Password" name="password" value={this.state.password} onChange={this.handleChange} required />
</div>
<div className="login-buttons">
<button type="submit" className="btn btn-success btn-block btn-lg" onClick={this.login}>Sign me in</button>
</div>
</form>
</div>
</div>
</React.Fragment>
)
}
}
export default withRouter(LoginV2);
You could use sessionStorage or localStorage to store the token and then check for it, if it is set then keep user logged in otherwise logout user.
set the session once user logged in
if (token) {
localStorage.setItem('session', JSON.stringify(token));
}
To check if the user is logged in
let user = localStorage.getItem('session');
if (user) {
console.log('Valid session');
} else {
console.log('Not valid session');
}
On logut clear the value
let user = localStorage.getItem('session');
if (user) {
localStorage.removeItem();
}
Adding the logic in the provided code
async handleSubmit(event) {
// .... Other code
const data = await getCred.json();
if (data.status == 400) {
alert(data);
} else {
this.handleSuccess(data);
}
console.log(data);
}
//Set your token in handleSuccess method
handleSuccess(data) {
alert("Logged IN");
if (data.token) {
localStorage.setItem('session', JSON.stringify(data.token));
}
this.props.history.push('dashboard/v2');
}

redux-form how to load data for editing

I am working with redux-form and it seems confusing me to load initial data for edit form but the data is not being validated on submit. I have managed to pass and load data into the fields but that seems not loading into the form props etc. Please see the following piece of code and let me know if need something more.
Form_Bayan.js
import React, {Component, PropTypes} from "react";
import {browserHistory} from "react-router";
import {reduxForm, Field} from "redux-form";
import {MyCustomInput, MySimpleInput, MyCustomSelect} from "./__form_field_components";
import {connect} from "react-redux";
import {bindActionCreators} from "redux";
import {
ADMIN_FETCH_AUTOSUGGESTS_Lbl,
adminFetchAutoSuggestCats_act,
ADMIN_GETCATID_BYNAME_Lbl,
adminGetCatIdByName_act,
ADMIN_ADDNEWBAYAAN_Lbl,
adminAddNewBayaan_act,
adminFetchArticlesByCat_act,
adminUpdateBayaan_act
} from "../../actions/adminActionCreators";
import _ from "lodash";
class NewBayanForm extends Component {
constructor(props) {
super(props);
this.state = {
submitButtonMeta: {
btnTitle: "Save",
btnClass: "btn btn-default",
btnIcon: null,
disabled: false
},
globalMessage: { // set when an action is performed by ActionCreation+Reducer and a message is returned
message: "",
className: ""
},
tempData: {
the_bayaansMainCat_id: this.props.associatedMainCatId, // being passed from parent component to avoide redundent declaration
the_autoSuggestCatList: [],
slug: "",
the_catId: null
}
};
}
resetMessageState() {
var noMsg = {message: "", className: ""};
this.setState({globalMessage: noMsg});
}
componentDidMount() {
this.props.adminFetchAutoSuggestCats_act(this.state.tempData.the_bayaansMainCat_id);
}
doSubmit(props) {
var newBayanObj = {
item_title: props.titleTxt,
item_slug: this.state.tempData.slug,
content: props.videoIdTxt,
picture: "",
attachment: "",
media_path: "https://www.youtube.com/watch?v=" + props.videoIdTxt,
reference: "",
tag_keywords: props.keywordsTxt,
author_name: props.authorTxt,
cat_id: this.state.tempData.the_catId
};
this.props.adminUpdateBayaan_act(newBayaanObj)
.then(() => {
this.props.adminFetchArticlesByCat_act(this.props.associatedMainCatId)
.then(() => {
this.props.toggleViewFunction(); // comming from Parent Class (bayaansPage)
});
});
}
fetchCategoryId(value) {
// make API call to fetch / generate category ID for this post
this.props.adminGetCatIdByName_act(value, this.state.tempData.the_bayaansMainCat_id); // '1': refers to look up under 'Bayaans' parent category for the specified category name
}
// will always receive and triggers when there are 'new props' and not old/same props
render() { // rendering Edit form
const {handleSubmit} = this.props;
console.log('<NewBayanForm> (render_editForm) this.props:', this.props);
return (
<div className="adminForm">
<form onSubmit={handleSubmit(this.doSubmit.bind(this))}>
<div className="col-sm-6">
<div className="row">
<div className="col-sm-5"><label>Title:</label></div>
<div className="col-sm-7"><Field name="titleTxt" component={MySimpleInput}
defaultValue={this.props.name} type="text"
placeholder="Enter Title"/></div>
</div>
<div className="row">
<div className="col-sm-5"><label>Slug:</label></div>
<div className="col-sm-7">{this.state.tempData.slug || this.props.slug} <input
type="hidden" name="slugTxt" value={this.state.tempData.slug}/></div>
</div>
<div className="row">
<div className="col-sm-5"><label>Select Category:</label></div>
<div className="col-sm-7"><Field name="catTxt" component={MyCustomSelect}
defaultValue={this.props.category_name} type="text"
placeholder="Select or Type a New"
selectableOptionsList={this.state.tempData.the_autoSuggestCatList}
onSelectionDone={ this.fetchCategoryId.bind(this) }/>
<input type="hidden" name="catIdTxt"
value={this.state.tempData.the_catId || this.props.category_id}/>
</div>
</div>
</div>
<div className="col-sm-6">
<div className="row">
<div className="col-sm-5"><label>Youtube Video ID:</label></div>
<div className="col-sm-7"><Field name="videoIdTxt" component={MySimpleInput}
defaultValue={this.props.content} type="text"
placeholder="TsQs9aDKwrw"/></div>
<div className="col-sm-12 hint"><b>Hint: </b> https://www.youtube.com/watch?v=<span
className="highlight">TsQs9aDKwrw</span></div>
</div>
<div className="row">
<div className="col-sm-5"><label>Author/Speaker:</label></div>
<div className="col-sm-7"><Field name="authorTxt" component={MySimpleInput}
defaultValue={this.props.author} type="text"/></div>
</div>
<div className="row">
<div className="col-sm-5"><label>Tags/Keywords:</label></div>
<div className="col-sm-7"><Field name="keywordsTxt" component={MySimpleInput}
defaultValue={this.props.tag_keywords} type="text"/>
</div>
</div>
</div>
<div className="row">
<div className={this.state.globalMessage.className}>{this.state.globalMessage.message}</div>
</div>
<div className="buttonControls">
<a className="cancelBtn" onClick={this.props.toggleViewFunction}>Cancel</a>
<button className={this.state.submitButtonMeta.btnClass}
disabled={this.state.submitButtonMeta.disabled}>
{this.state.submitButtonMeta.btnTitle}</button>
</div>
</form>
</div>
);
}
}
function validate(values) { // Validate function being called on Blur
const errors = {};
if (!values.titleTxt)
errors.titleTxt = "Enter Title";
if (!values.catTxt)
errors.catTxt = "Select/Enter a Category";
if (!values.videoIdTxt)
errors.videoIdTxt = "Enter youtube video ID (follow the provided hint)";
if (!values.keywordsTxt)
errors.keywordsTxt = "Enter keywords (will help in search)";
return errors;
}
// ReduxForm decorator
const newBayanFormAdmin_reduxformObj = reduxForm({
form: "newBayanFormAdmin", // any unique name of our form
validate // totally equivelent to--> validate: validate
});
function mapStateToProps({siteEssentials}, ownProps) {
// 1st param is related to our Redux State, 2nd param relates to our own component props
var initialValues = {
titleTxt: ownProps.name,
slugTxt: ownProps.slug,
catTxt: ownProps.category_name,
catIdTxt: ownProps.category_id,
videoIdTxt: ownProps.content,
authorTxt: ownProps.author,
keywordsTxt: ownProps.tag_keywords
};
return ({siteEssentials}, initialValues);
};
function mapDispatchToProps(dispatch) {
return bindActionCreators({
adminFetchAutoSuggestCats_act,
adminGetCatIdByName_act,
adminAddNewBayaan_act,
adminFetchArticlesByCat_act
}, dispatch);
};
NewBayanForm = connect(mapStateToProps, mapDispatchToProps) (newBayanFormAdmin_reduxformObj(NewBayanForm));
export default NewBayanForm;
try initialValues for more details
inside reduxform :
export default NewBayanForm = reduxForm({ form: 'NewBayanForm', initialValues: {
name: "abc",
email: "abc#gmail.com",
phoneNo: "1234567890"
} })(NewBayanForm)
or
<NewBayanForm initialValues={yourObject} />
I found this tutorial which is quite simple and helpful.
https://www.davidmeents.com/?p=38

OnChange event handlers don't get called when I'm updating a form

I have a form that should update my applications state as a user types in the input field and in the textarea. The input and textarea call their event handlers through onChange={event handler}. For some reason when I type in either field the event handlers don't get called at all. The input and textarea fields seem to work fine outside of a form though.
import React, { Component, PropTypes } from 'react';
import { reduxForm } from 'redux-form';
import { connect } from 'react-redux';
import LogoutHeader from './LogoutHeader';
import { fetchTodo, updateTodo, deleteTodo } from '../actions/index';
import { Link } from 'react-router';
class ShowTodo extends Component {
static contextTypes = {
router: PropTypes.object
};
constructor(props) {
super(props);
this.state = {
descriptionChanged: false,
newDescription: '',
newTitle: '',
done: false,
id: 0
};
this.handleDescriptionChange = this.handleDescriptionChange.bind(this);
this.handleDeleteClick = this.handleDeleteClick.bind(this);
this.changeButtons = this.changeButtons.bind(this);
this.handleSaveClick = this.handleSaveClick.bind(this);
this.handleUndoClick = this.handleUndoClick.bind(this);
this.handleTitleChange = this.handleTitleChange.bind(this);
this.handleDoneChange = this.handleDoneChange.bind(this);
}
componentWillMount() {
this.props.fetchTodo(this.props.params.id).then(() => {
this.setState({
newDescription: this.props.todo.description,
newTitle: this.props.todo.title,
done: this.props.todo.completed,
id: this.props.todo.id
});
});
}
render() {
const { todo } = this.props;
const { fields: {title, description}, handleSubmit } = this.props;
console.log("Fields: description: ", this.props.fields.description.value); //These values change as expected
console.log("Fields: title: ", this.props.fields.title.value);
if (!todo) {
return (
<h3>Loading...</h3>
);
}
return (
<div id="showTodo">
<Link id="btnBack" className="btn btn-custom" role="button" to="/todos_index"><span className="glyphicon glyphicon-arrow-left"></span></Link>
<LogoutHeader></LogoutHeader>
<div className="row">
<div className="col-md-6 col-md-offset-3">
<form onSubmit={handleSubmit(this.handleSaveClick)}>
<h3>Edit Todo</h3>
<div className={`form-group ${title.touched && title.invalid ? 'has-danger' : ''}`}>
<label>Title</label>
<input
type="text"
className="form-control"
value={this.state.newTitle}
onChange={this.handleTitleChange}
{...title} />
</div>
<div className="text-help">
{description.touched ? description.error : ''}
</div>
<div className={`form-group ${description.touched && description.invalid ? 'has-danger' : ''}`}>
<label>Description</label>
<textarea
className="form-control"
value={this.state.newDescription}
onChange={this.handleDescriptionChange}
{...description} >
</textarea>
</div>
<div className="text-help">
{description.touched ? description.error : ''}
</div>
<span className="input-group-btn">
{this.changeButtons()}
<button id="editTodoDelete" className="btn btn-custom" onClick={this.handleDeleteClick}><span className="glyphicon glyphicon-trash"></span></button>
</span>
</form>
</div>
</div>
</div>
);
}
changeButtons() { //This does not get called when there are changed in the input or textareas.
if (!this.state.descriptionChanged) {
return null;
} else {
return [
<button
type="submit"
id="editTodoSave"
className="btn btn-custom"
><span className="glyphicon glyphicon-floppy-save"></span></button>,
<button
id="editTodoRefresh"
className="btn btn-custom"
onClick={this.handleUndoClick}
><span className="glyphicon glyphicon-refresh"></span></button>
];
}
}
handleDescriptionChange(event) { //This does not get called when there is a change in the textarea
this.setState({
descriptionChanged: true,
newDescription: this.props.fields.description.value
});
}
handleTitleChange(event) { //This does not get called when there is a changed in the input field.
this.setState({
descriptionChanged: true,
newTitle: this.props.fields.title.value
});
}
handleDoneChange() {
this.setState({
done: !this.state.done
});
var props = {
completed: this.state.done
};
this.props.updateTodo(this.state.id, JSON.stringify(props));
}
handleDeleteClick() {
this.props.deleteTodo(this.state.id).then(() => {
this.context.router.push('/todos_index');
});
}
handleSaveClick(props) {
this.props.updateTodo(this.state.id, JSON.stringify(props)).then(() => {
alert("Todo updates should have been recieved in database");
this.context.router.push('/todos_index');
});
}
handleUndoClick() {
this.setState({
descriptionChanged: false,
newTitle: this.props.todo.title,
newDescription: this.props.todo.description,
errors: {
title: '',
description: ''
}
});
}
}
function validate(values) {
const errors = {};
if (!values.title) {
errors.title = 'Please enter a title';
}
if (values.title) {
if (values.title.length > 25){
errors.title = 'You exceeded 25 characters';
}
}
if (!values.description) {
errors.description = 'Please enter your description';
}
if (values.description) {
if (values.description.length > 500) {
errors.description = "You exceeded 500 characters";
}
}
return errors;
}
function mapStateToProps(state) {
return { todo: state.todos.todo };
}
export default reduxForm({
form: 'ShowTodoForm',
fields: ['title', 'description'],
validate //These configurations will be added to the application state, so reduxForm is very similar to the connect function.
//connect: first argument is mapStateToProps, second is mapDispatchToProps
//reduxForm: 1st is form configuration, 2nd is mapStateToProps, 3rd is mapDispatchToProps
}, mapStateToProps, { fetchTodo, updateTodo, deleteTodo })(ShowTodo);

Call function from a separate class in REACT JS

I am learning REACT and am having some trouble.
I have multiple pages/components each of these pages has a form in it and I have written a function to handle the form input once submitted.
However i would like to move this function to its own component this way each of the pages simply calls this single component when the form is submitted.
My question is how to do accomplish this using REACT, I have been searching for hours and just cannot figure it out.
Here are two example components:
Form handler/form processing
'use strict';
import React from 'react/addons';
const FormProcessing = React.createClass({
_test: function() {
console.log('test');
//do something with form values here
},
render(){
}
});
export default FormProcessing;
Example component with form, that needs to call the 'test' function from the 'FormProcessing' component
'use strict';
import React from 'react/addons';
import {Link} from 'react-router';
import DocumentTitle from 'react-document-title';
const BreakingNewsPage = React.createClass({
propTypes: {
currentUser: React.PropTypes.object.isRequired
},
_inputFields: function() {
return (
<form id="breakingNewsForm" action="" onclick={call test function from form processing component}>
<fieldset>
<legend>Headline</legend>
<div className="form-group">
<input type="text" className="form-control input-size-md" id="inputHeadline" placeholder="Headline (Example: Budget Cuts)"/>
</div>
<legend>Breaking News</legend>
<div class="form-group">
<input type="text" className="form-control input-size-lg" id="inputDescription1" placeholder="Breaking News Description"/>
<input type="text" className="form-control input-size-lg" id="inputDescription2" placeholder="Breaking News Description"/>
</div>
</fieldset>
</form>
);
},
_formButtons: function() {
return (
<div className="form-buttons">
<button form="breakingNewsForm" type="reset" className="btn-lg">Clear</button>
<button form="breakingNewsForm" type="submit" classn="btn-lg">Save</button>
</div>
);
},
render() {
return (
<DocumentTitle title="Breaking News">
<section className="ticker-page page container-fluid">
<div className="page-title">
<h1>Breaking News</h1>
</div>
<div className="com-md-6">
{this._inputFields()}
{this._formButtons()}
</div>
</section>
</DocumentTitle>
);
}
});
export default BreakingNewsPage;
Updated code using example provided by: ycavatars
This class renders the form and a few other bits, I have now required the 'FormProcessing class' and have assigned it to _formHandler: FormProcessing,
I then try and call the function handleForm from the formProcessing class using this._formHandler.handleForm(); but i receive this error: Uncaught TypeError: this._formHandler.handleForm is not a function
'use strict';
import React from 'react/addons';
import {Link} from 'react-router';
import DocumentTitle from 'react-document-title';
var FormProcessing = require ('../components/FormProcessing.js');
const IntroPage = React.createClass({
propTypes: {
currentUser: React.PropTypes.object.isRequired
},
_formHandler: FormProcessing,
// initial state of form
getInitialState: function() {
return {
type: 'info',
message: ''
};
},
// handles the form callback
_handleSubmit: function (event) {
event.preventDefault();
// Scroll to the top of the page to show the status message.
this.setState({ type: 'info', message: 'Saving...' }, this._sendFormData);
},
// sends form data to server
_sendFormData: function () {
this._formHandler._handleForm();
this.setState({ type: 'success', message: 'Form Successfully Saved' });
return;
},
_inputFields: function() {
var rows = [];
for(var i = 1; i <= 12; i++) {
var placeHolder = 'Intro text line ' + i;
var inputID = 'inputIntroText ' + i;
rows.push(<input type="text" className="form-control input-size-lg" name="formInput" id={inputID} placeholder={placeHolder}/>);
}
return (
<form id="introForm" action="" onSubmit={this._handleSubmit}>
<fieldset>
<legend>Intro Title</legend>
<div className="form-group">
<input type="text" className="form-control input-size-md" name="formInput" id="introTitle" placeholder="Intro Title"/>
</div>
<legend>Intro Text</legend>
<div className="form-group">
{rows}
</div>
</fieldset>
</form>
);
},
_formButtons: function() {
return (
<div className="form-buttons">
<button form="introForm" type="reset" className="btn-lg">Clear</button>
<button form="introForm" type="submit" className="btn-lg">Save</button>
</div>
);
},
render() {
// checks and displays the forms state
if (this.state.type && this.state.message) {
var classString = 'alert alert-' + this.state.type;
var status = <div id="status" className={classString} ref="status">
{this.state.message}
</div>;
}
return (
<DocumentTitle title="Intro">
<section className="intro-page page container-fluid">
<div className="page-title">
<h1>Intro</h1>
</div>
<div className="com-md-6">
{status}
{this._inputFields()}
{this._formButtons()}
</div>
</section>
</DocumentTitle>
);
}
});
export default IntroPage;
This is the FormProcessing class
'use strict';
import React from 'react/addons';
var IntroPage = require ('../pages/IntroPage.js')
class FormProcessing extends React.Component {
_handleForm() {
console.log('you caled me!');
}
};
export default FormProcessing;
You want to invoke FormProcessing._test from BreakingNewsPage component. You have to know the difference between class and instance. React.createClass returns a class which describes your component, and the render method of your component returns a virtual DOM element.
In order to call FormProcessing._test, you have to get the reference to the backing instance of FormProcessing class. That's why react provides a ref. The official tutorial explains the details.
There's an open source project, how to center in css, uses many ref. You could take a look.

Dynamically load initialValues in Redux Form

Using the example of initializingFromState within Redux-Form, I am trying to set this up dynamically. This is to edit a particular book in a list of books, and is using a simple api set up in express.js.
The full container is below. I somehow need to pass in initialValues, within the mapStateToProps function. In the example, it is done via a static object, but I can't work out how to use the information I have pulled in via fetchBook, and pass it to initialValues.
Container:
import React, { Component, PropTypes } from 'react';
import { reduxForm } from 'redux-form';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import { fetchBook, editBook } from '../actions/index';
class BookEdit extends Component {
componentWillMount() {
this.props.fetchBook(this.props.params.id);
}
static contextTypes = {
router: PropTypes.object
}
onSubmit(props) {
this.props.editBook(this.props.book.id, props)
.then(() => {
this.context.router.push('/');
});
}
const data = {
title: {this.props.book.title},
description: {this.props.author}
}
render() {
const { fields: { title, author }, handleSubmit } = this.props;
const { book } = this.props;
if (!book) {
return (
<div>
<p>Loading...</p>
</div>
)
}
return (
<div>
<Link to="/">Back</Link>
<form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
<h2>Add a new book</h2>
<label>Title</label>
<input type="text" {...title} />
<div className="text-help">{title.touched ? title.error : ''}</div>
<label>Author</label>
<input type="text" {...author} />
<div className="text-help">{author.touched ? author.error : ''}</div>
<button type="submit">Add</button>
<Link to="/" className="button">Go back</Link>
</form>
</div>
);
}
}
function mapStateToProps(state) {
return {
book: state.books.book,
initialValues: // how do I pass in the books here?
};
}
export default reduxForm({
form: 'EditBookForm',
fields: ['title', 'author']
}, mapStateToProps, { fetchBook, editBook })(BookEdit);
Thank you.
Your form values aren't what's in state.books.book? I think this is all you're looking for:
function mapStateToProps(state) {
return {
book: state.books.book,
initialValues: state.books.book
};
}
Since you're only really looking at this.props.book to know if it's loaded or not, it might be more explicit to do something like:
function mapStateToProps(state) {
return {
loaded: !!state.books.book,
initialValues: state.books.book
};
}
Hope that helps.
In related to above question, Erik. I have following form and not sure why it is not Validating on submit. It loads the data into fields but when I hit submit the validation fails.
Form_Bayan.js
import React, {Component, PropTypes} from "react";
import {browserHistory} from "react-router";
import {reduxForm, Field} from "redux-form";
import {MyCustomInput, MySimpleInput, MyCustomSelect} from "./__form_field_components";
import {connect} from "react-redux";
import {bindActionCreators} from "redux";
import {
ADMIN_FETCH_AUTOSUGGESTS_Lbl,
adminFetchAutoSuggestCats_act,
ADMIN_GENERATESLUG_Lbl,
adminGenerateSlug_act,
ADMIN_GETCATID_BYNAME_Lbl,
adminGetCatIdByName_act,
ADMIN_ADDNEWBAYAAN_Lbl,
adminAddNewBayaan_act,
adminFetchArticlesByCat_act,
adminUpdateBayaan_act
} from "../../actions/adminActionCreators";
import _ from "lodash";
class NewBayanForm extends Component {
constructor(props) {
super(props); // this component inherits "toggleViewFunction" function through props for redirection
this.generateSlug = this.generateSlug.bind(this);
this.state = {
submitButtonMeta: {
btnTitle: "Save",
btnClass: "btn btn-default",
btnIcon: null,
disabled: false
},
globalMessage: { // set when an action is performed by ActionCreation+Reducer and a message is returned
message: "",
className: ""
},
tempData: {
//the_bayaansMainCat_id : 1, // '1' refers to the 'Bayaans' parent category in admin , this ID is used here for different sort of lookups i.e. fetch available subcats for autosuggest, fetch cat ID by name under parent catID
the_bayaansMainCat_id: this.props.associatedMainCatId, // being passed from parent component to avoide redundent declaration
the_autoSuggestCatList: [],
slug: "",
the_catId: null
}
};
}
resetMessageState() {
var noMsg = {message: "", className: ""};
this.setState({globalMessage: noMsg});
}
componentDidMount() {
console.log("<NewBayanForm> (componentDidMount)");
this.props.adminFetchAutoSuggestCats_act(this.state.tempData.the_bayaansMainCat_id);
}
doSubmit(props) {
//console.log("----- submitting form -----");
//console.log(props);
this.disableSubmitButton();
// prepare data for submit request
// item_title, item_slug, content, picture, attachment, media_path, reference, tag_keywords, author_name, cat_id, date_created
var newBayanObj = {
item_title: props.titleTxt,
item_slug: this.state.tempData.slug,
content: props.videoIdTxt,
picture: "",
attachment: "",
media_path: "https://www.youtube.com/watch?v=" + props.videoIdTxt,
reference: "",
tag_keywords: props.keywordsTxt,
author_name: props.authorTxt,
cat_id: this.state.tempData.the_catId
};
this.props.adminUpdateBayaan_act(newBayaanObj)
.then(() => {
console.log("%c <NewBayanForm> (doSubmit) Updated bayaan, refetching updated bayaans list...", "color:blue;font-weight:bold;");
this.props.adminFetchArticlesByCat_act(this.props.associatedMainCatId)
.then(() => {
console.log("%c <NewBayanForm> (doSubmit) Redirecting to Gallery after update...", "color:blue;font-weight:bold;");
this.props.toggleViewFunction(); // comming from Parent Class (bayaansPage)
});
});
}
disableSubmitButton() {
console.log("<NewBayanForm> (disableSubmitButton)");
// Ref: http://stackoverflow.com/questions/18933985/this-setstate-isnt-merging-states-as-i-would-expect
var newButtonState = {
btnTitle: "Please wait... ",
btnClass: "btn btn-disabled",
btnIcon: null,
disabled: true
};
this.setState({submitButtonMeta: newButtonState});
this.resetMessageState(); // Need to reset message state when retrying for form submit after 1st failure
}
enableSubmitButton() {
console.log("<NewBayanForm> (enableSubmitButton)");
// Ref: http://stackoverflow.com/questions/18933985/this-setstate-isnt-merging-states-as-i-would-expect
var newButtonState = {btnTitle: "Save", btnClass: "btn btn-default", btnIcon: null, disabled: false};
this.setState({submitButtonMeta: newButtonState});
}
fetchCategoryId(value) {
console.log('<NewBayanForm> (fetchCategoryId) input-Value:', value); // make API call to fetch / generate category ID for this post
this.props.adminGetCatIdByName_act(value, this.state.tempData.the_bayaansMainCat_id); // '1': refers to look up under 'Bayaans' parent category for the specified category name
}
// will always receive and triggers when there are 'new props' and not old/same props
componentWillReceiveProps(nextProps) { // required when props are passed/changed from parent source. And we want to do some operation as props are changed (Ref: http://stackoverflow.com/questions/32414308/updating-state-on-props-change-in-react-form)
console.log("<NewBayanForm> (componentWillReceiveProps) nextProps: ", nextProps); // OK
//console.log("this.props : ", this.props); // OK
//console.log("nextProps.siteEssentials.actionsResult : ", nextProps.siteEssentials.actionsResult); // OK
if (nextProps.hasOwnProperty("siteEssentials")) { // if action status appeared as Done!
if (nextProps.siteEssentials.hasOwnProperty("actionsResult")) { // if action status appeared as Done!
if (nextProps.siteEssentials.actionsResult[ADMIN_GETCATID_BYNAME_Lbl] !== "FAILED") {
var clonedState = this.state.tempData;
clonedState.the_catId = nextProps.siteEssentials.actionsResult[ADMIN_GETCATID_BYNAME_Lbl];
//var newTempState = {slug: this.state.tempData.slug, the_catId: nextProps.siteEssentials.actionsResult[ADMIN_GETCATID_BYNAME_Lbl] };
this.setState({tempData: clonedState});
}
if (nextProps.siteEssentials.actionsResult[ADMIN_FETCH_AUTOSUGGESTS_Lbl] !== "FAILED") {
var clonedState = this.state.tempData;
clonedState.the_autoSuggestCatList = nextProps.siteEssentials.actionsResult[ADMIN_FETCH_AUTOSUGGESTS_Lbl];
this.setState({tempData: clonedState});
}
console.log("<NewBayanForm> (componentWillReceiveProps) new-State:", this.state);
}
}
}
render() { // rendering Edit form
const {handleSubmit} = this.props;
console.log('<NewBayanForm> (render_editForm) this.props:', this.props);
return (
<div className="adminForm">
<form onSubmit={handleSubmit(this.doSubmit.bind(this))}>
<div className="col-sm-6">
<div className="row">
<div className="col-sm-5"><label>Title:</label></div>
<div className="col-sm-7"><Field name="titleTxt" component={MySimpleInput}
defaultValue={this.props.name} type="text"
placeholder="Enter Title"/></div>
</div>
<div className="row">
<div className="col-sm-5"><label>Slug:</label></div>
<div className="col-sm-7">{this.state.tempData.slug || this.props.slug} <input
type="hidden" name="slugTxt" value={this.state.tempData.slug}/></div>
</div>
<div className="row">
<div className="col-sm-5"><label>Select Category:</label></div>
<div className="col-sm-7"><Field name="catTxt" component={MyCustomSelect}
defaultValue={this.props.category_name} type="text"
placeholder="Select or Type a New"
selectableOptionsList={this.state.tempData.the_autoSuggestCatList}
onSelectionDone={ this.fetchCategoryId.bind(this) }/>
<input type="hidden" name="catIdTxt"
value={this.state.tempData.the_catId || this.props.category_id}/>
</div>
</div>
</div>
<div className="col-sm-6">
<div className="row">
<div className="col-sm-5"><label>Youtube Video ID:</label></div>
<div className="col-sm-7"><Field name="videoIdTxt" component={MySimpleInput}
defaultValue={this.props.content} type="text"
placeholder="TsQs9aDKwrw"/></div>
<div className="col-sm-12 hint"><b>Hint: </b> https://www.youtube.com/watch?v=<span
className="highlight">TsQs9aDKwrw</span></div>
</div>
<div className="row">
<div className="col-sm-5"><label>Author/Speaker:</label></div>
<div className="col-sm-7"><Field name="authorTxt" component={MySimpleInput}
defaultValue={this.props.author} type="text"/></div>
</div>
<div className="row">
<div className="col-sm-5"><label>Tags/Keywords:</label></div>
<div className="col-sm-7"><Field name="keywordsTxt" component={MySimpleInput}
defaultValue={this.props.tag_keywords} type="text"/>
</div>
</div>
</div>
<div className="row">
<div className={this.state.globalMessage.className}>{this.state.globalMessage.message}</div>
</div>
<div className="buttonControls">
<a className="cancelBtn" onClick={this.props.toggleViewFunction}>Cancel</a>
<button className={this.state.submitButtonMeta.btnClass}
disabled={this.state.submitButtonMeta.disabled}>
{this.state.submitButtonMeta.btnTitle}</button>
</div>
</form>
</div>
);
}
}
function validate(values) { // Validate function being called on Blur
const errors = {};
if (!values.titleTxt)
errors.titleTxt = "Enter Title";
if (!values.catTxt)
errors.catTxt = "Select/Enter a Category";
if (!values.videoIdTxt)
errors.videoIdTxt = "Enter youtube video ID (follow the provided hint)";
if (!values.keywordsTxt)
errors.keywordsTxt = "Enter keywords (will help in search)";
return errors;
}
// ReduxForm decorator
const newBayanFormAdmin_reduxformObj = reduxForm({
form: "newBayanFormAdmin", // any unique name of our form
validate // totally equivelent to--> validate: validate
});
function mapStateToProps({siteEssentials}, ownProps) {
console.log("<NewBayanForm> (mapStateToProps) siteEssentials:", siteEssentials);
// 1st param is related to our Redux State, 2nd param relates to our own component props
var initialValues = {
titleTxt: ownProps.name,
slugTxt: ownProps.slug,
catTxt: ownProps.category_name,
catIdTxt: ownProps.category_id,
videoIdTxt: ownProps.content,
authorTxt: ownProps.author,
keywordsTxt: ownProps.tag_keywords
};
console.log("<NewBayanForm> (mapStateToProps) initialValues: ", initialValues);
return ({siteEssentials}, initialValues);
};
function mapDispatchToProps(dispatch) {
return bindActionCreators({
adminFetchAutoSuggestCats_act,
adminGenerateSlug_act,
adminGetCatIdByName_act,
adminAddNewBayaan_act,
adminFetchArticlesByCat_act
}, dispatch);
};
NewBayanForm = connect(mapStateToProps, mapDispatchToProps) (newBayanFormAdmin_reduxformObj(NewBayanForm));
export default NewBayanForm;

Categories