Skip to content

Instantly share code, notes, and snippets.

@LuizMoreira
Last active December 29, 2015 12:23
Show Gist options
  • Save LuizMoreira/28b9d49920bc2b0c31df to your computer and use it in GitHub Desktop.
Save LuizMoreira/28b9d49920bc2b0c31df to your computer and use it in GitHub Desktop.
Error setState - lines 401-408
import { createHistory, useBasename } from 'history'
import { Router, Route, Link, History, Lifecycle } from 'react-router'
import classNames from 'classnames';
import SidebarMixin from 'global/jsx/sidebar_component';
import Header from 'common/header';
import Sidebar from 'common/sidebar';
import Footer from 'common/footer';
import Helpers from '../util/Helpers';
import auth from '../util/auth'
var Body = React.createClass({
mixins: [ History ],
// statics: {
// willTransitionTo: function(transition){
// console.log('atualizaCliente willTransitionTo -->'+ transition);
// if(!auth.loggedIn()){
// transition.redirect('/app/login');
// }
// }
// },
propTypes:{
callBackLogin: React.PropTypes.func.isRequired
},
getInitialState: function(){
console.log('login - getInitialState ');
return {
cliente:{},
returnStatus:{},
loggedIn: auth.loggedIn(),
error: false
};
},
updateAuth(loggedIn) {
this.setState({
loggedIn: loggedIn
})
},
callBackLogin:function(){
this.props.callBackLogin(this.state.cliente);
},
//login pixma
submitPixma: function(e) {
e.preventDefault();
e.stopPropagation();
if($('#form').valid()){
self = this
console.log('React.getDOMNode(this.refs.email).value = ' +React.findDOMNode(this.refs.email).value);
console.log('React.getDOMNode(this.refs.senha).value = ' +React.findDOMNode(this.refs.senha).value);
var data = {
email: React.findDOMNode(this.refs.email).value,
senha: React.findDOMNode(this.refs.senha).value
}
Helpers.Post('/cliente/autentica', data, this.success, this.error)
}
},
//retorno de sucesso do Helpers
success: function (result) {
console.log('++++++ logou!!! ++++' + result.dataObject.codigo)
if(this.isMounted()){
this.setState({
cliente: result.dataObject,
resultStatus: result.resultStatus
});
console.log('STATE CLIENTE'+ this.state.cliente.nome);
this.callBackLogin();
auth.login(this.state.cliente.email, React.findDOMNode(this.refs.senha).value , (loggedIn) => {
if (loggedIn){
console.log('LOGIN COOKIE --> PASSOU -->'+ loggedIn);
if(!result.returnStatus.isError){
//https://github.com/rackt/react-router/blob/latest/examples/transitions/app.js
this.history.pushState(null, '/app/atualizaCliente');
}
}
})
}
},
//retorno de erro do Helpers
error: function (xhr, textStatus, errorThrown) {
React.findDOMNode(this.refs.senha).value= '';
vex.dialog.alert(xhr.returnStatus.description);
},
clearForm: function() {
this.setState({
cliente: {},
resultStatus: {},
email: "",
senha: ""
});
},
submitTwitter: function(e) {
e.preventDefault();
if($('#form').valid()){
e.stopPropagation();
this.transitionTo('/app/wizard');
}
},
submitFacebook: function(e) {
e.preventDefault();
if($('#form').valid()){
e.stopPropagation();
this.transitionTo('/app/wizard');
}
},
componentDidMount: function() {
$('html').addClass('authentication');
$('#form').validate({
rules: {
txtEmail: {
required: true,
email: true
},
txtSenha: {
required: true,
minlength:6
}
},
messages: {
txtEmail: {
required: "Email é obrigatório",
email: "Email ta errado....",
remote: 'email já existente'
},
txtSenha: {
required: "Senha é um campo obrigatório",
minlength: "É necessário informar ao menos 6 caracteres para o campo senha."
}
},
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function(error, element) {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
},
componentWillUnmount: function() {
$('html').removeClass('authentication');
},
render: function() {
return (
<Container id='auth-container' className='login'>
<Container id='auth-row'>
<Container id='auth-cell'>
<Grid>
<Row>
<Col sm={12}>
<PanelContainer noControls>
<Panel>
<PanelBody style={{padding: 0}}>
<div className='text-center bg-darkblue fg-white'>
<h3 style={{margin: 0, padding: 25}}>Logar no <img src='/imgs/logo.png' alt='Pixma' width='111' height='28' /></h3>
</div>
<div className='bg-hoverblue fg-black50 text-center' style={{padding: 12.5}}>
<div>Você precisa logar para obter orçamento</div>
<div style={{marginTop: 12.5, marginBottom: 12.5}}>
<Button id='facebook-btn' lg bsStyle='darkblue' type='submit' onClick={this.back}>
<Icon glyph='icon-fontello-facebook' />
<span>Logar <span className='hidden-xs'>com facebook</span></span>
</Button>
</div>
<div>
<a id='twitter-link' href='#' onClick={this.submitPixma}><Icon glyph='icon-fontello-twitter' /><span> ou com twitter</span></a>
</div>
</div>
<div>
<div className='text-center' style={{padding: 12.5}}>
ou use sua conta no Pixma
</div>
<div style={{padding: 25, paddingTop: 0, paddingBottom: 0, margin: 'auto', marginBottom: 25, marginTop: 25}}>
<Form id='form' onSubmit={this.submitPixma} >
<FormGroup>
<InputGroup lg>
<InputGroupAddon>
<Icon glyph='icon-fontello-mail' />
</InputGroupAddon>
<Input autoFocus type='email' id='txtEmail' name='txtEmail' ref='email' className='border-focus-blue' placeholder='pixma@pixma.com.br' />
</InputGroup>
</FormGroup>
<FormGroup>
<InputGroup lg>
<InputGroupAddon>
<Icon glyph='icon-fontello-key' />
</InputGroupAddon>
<Input type='password' id='txtSenha' name='txtSenha' ref='senha' className='border-focus-blue' placeholder='password' />
</InputGroup>
</FormGroup>
<FormGroup>
<Grid>
<Row>
<Col xs={6} collapseLeft collapseRight style={{paddingTop: 10}}>
<Link to='/app/signup'>Criar uma conta Pixma</Link>
</Col>
<Col xs={6} collapseLeft collapseRight className='text-right'>
<Button outlined lg type='submit' bsStyle='blue' onClick={this.submitPixma} >Logar</Button>
</Col>
</Row>
</Grid>
</FormGroup>
</Form>
</div>
</div>
</PanelBody>
</Panel>
</PanelContainer>
</Col>
</Row>
</Grid>
</Container>
</Container>
</Container>
);
}
});
@SidebarMixin
export default class extends React.Component {
// static propTypes : {
// cliente: React.PropTypes.object.isRequired
// }
constructor(props) {
super(props);
this.state = {
cliente: {}
};
}
didObterLogin(clienteLogin){
console.log('didObterLogin --'+clienteLogin.nome);
this.setState({
cliente: clienteLogin
});
}
componentWillUnmount () {
//console.log('login mesmo --'+props.cliente);
console.log('componentWillUnmount --'+this.state.cliente.nome);
}
render() {
var classes = classNames({
'container-open': this.props.open
});
return (
<Container id='container' className={classes}>
<Sidebar/>
<Header />
<Body callBackLogin={this.didObterLogin.bind(this)} />
<Footer />
</Container>
);
}
}
import { Link, History } from 'react-router';
import classNames from 'classnames';
var global_delay = 300;
var openState = (!Modernizr.touch) ? (localStorage.getItem('sidebar-open-state') === 'true' ? true : false) : false;
export default function SidebarMixin(ComposedComponent) {
return React.createClass({
displayName: 'SidebarMixin',
getInitialState() {
return {
open: openState
};
},
isOpen() {
return this.state.open === open;
},
sidebarStateChangeCallback(open) {
if(this.isOpen()) return;
if(open !== undefined) {
openState = open;
} else {
openState = !this.state.open;
}
this.setState({
open: openState // toggle sidebar
});
localStorage.setItem('sidebar-open-state', openState);
},
componentWillMount() {
ReactBootstrap.Dispatcher.on('sidebar', this.sidebarStateChangeCallback);
},
componentWillUnmount() {
ReactBootstrap.Dispatcher.off('sidebar', this.sidebarStateChangeCallback);
},
render() {
return <ComposedComponent {...this.props} open={this.state.open} />;
}
});
}
export var SidebarControlBtn = React.createClass({
getInitialState() {
return {
active: this.props.active || false
};
},
handleClick(e) {
e.preventDefault();
e.stopPropagation();
ReactBootstrap.Dispatcher.emit('sidebar:controlbtn', this.props);
ReactBootstrap.Dispatcher.emit('sidebar:keychange', this.props.sidebar);
},
handleState(props) {
if(props.hasOwnProperty('sidebar')) {
if(props.sidebar === this.props.sidebar) {
this.setState({active: true});
} else {
this.setState({active: false});
}
}
},
componentDidMount() {
ReactBootstrap.Dispatcher.on('sidebar:controlbtn', this.handleState);
var scrollToTop = () => {
if($(window).scrollTop() === 0) return;
setTimeout(() => {
$('html, body, #body').scrollTop(0);
$(window).scrollTop(0);
scrollToTop();
}, 15);
};
scrollToTop();
},
componentWillUnmount() {
ReactBootstrap.Dispatcher.off('sidebar:controlbtn', this.handleState);
},
render() {
var classes = classNames('sidebar-control-btn', {
'active': this.state.active
}, this.props.className);
var props = {
tabIndex: '-1',
onClick: this.handleClick,
...this.props,
className: classes.trim()
};
return (
<li {...props}>
<a href='#' tabIndex='-1'>
<Icon bundle={this.props.bundle} glyph={this.props.glyph}/>
</a>
</li>
);
}
});
export var SidebarControls = React.createClass({
render() {
var classes = classNames('sidebar-controls-container',
this.props.className);
var props = {
dir: 'ltr',
...this.props,
className: classes
};
return (
<div {...props} children={null}>
<div className='sidebar-controls' tabIndex='-1'>
{this.props.children}
</div>
</div>
);
}
});
var timer = null;
export var Sidebar = React.createClass({
getInitialState() {
return {
left: ((this.props.sidebar * 100) + '%'),
visibility: (this.props.sidebar === 0) ? 'visible' : 'hidden'
};
},
handleKeyChange(sidebar) {
var newLeft = ((this.props.sidebar*100) - (sidebar*100))+'%';
this.setState({
left: newLeft,
visibility: 'visible'
}, () => {
if(newLeft !== '0%') {
setTimeout(() => {
this.setState({visibility: 'hidden'});
}, global_delay);
} else if(newLeft === '0%') {
var height = $(ReactDOM.findDOMNode(this.refs.innersidebar)).height();
if($('html').hasClass('static')) {
$('#body').css('min-height', height+400);
} else {
$('#body').css('min-height', '');
}
}
});
},
updateScrollbar() {
if(!Modernizr.touch) {
$(ReactDOM.findDOMNode(this.refs.sidebar)).perfectScrollbar('update');
}
},
repositionScrollbar(child_node, top, height) {
clearTimeout(timer);
var node = $(ReactDOM.findDOMNode(this.refs.sidebar));
var scrollTo = top - node.offset().top + node.scrollTop();
if(node.find(child_node).length) {
if(scrollTo > ($(window).height() / 2)) {
this.timer = setTimeout(() => {
node.scrollTop(scrollTo - ($(window).height() / 2) + 100);
}, 15);
}
}
if(!Modernizr.touch) {
this.updateScrollbar();
}
},
destroyScrollbar() {
$(ReactDOM.findDOMNode(this.refs.sidebar)).perfectScrollbar('destroy');
},
initializeScrollbar() {
$(ReactDOM.findDOMNode(this.refs.sidebar)).perfectScrollbar({
suppressScrollX: true
});
},
componentWillMount() {
ReactBootstrap.Dispatcher.on('sidebar:reinitialize', this.initializeScrollbar);
ReactBootstrap.Dispatcher.on('sidebar:destroy', this.destroyScrollbar);
ReactBootstrap.Dispatcher.on('sidebar:update', this.updateScrollbar);
ReactBootstrap.Dispatcher.on('sidebar:reposition', this.repositionScrollbar);
ReactBootstrap.Dispatcher.on('sidebar:keychange', this.handleKeyChange);
},
componentDidMount() {
if(!Modernizr.touch) {
this.initializeScrollbar();
}
if(this.props.active) {
setTimeout(() => {
ReactBootstrap.Dispatcher.emit('sidebar:controlbtn', {sidebar: this.props.sidebar});
ReactBootstrap.Dispatcher.emit('sidebar:keychange', this.props.sidebar);
}, 15);
}
},
componentWillUnmount() {
ReactBootstrap.Dispatcher.off('sidebar:reinitialize', this.initializeScrollbar);
ReactBootstrap.Dispatcher.off('sidebar:destroy', this.destroyScrollbar);
ReactBootstrap.Dispatcher.off('sidebar:update', this.updateScrollbar);
ReactBootstrap.Dispatcher.off('sidebar:reposition', this.repositionScrollbar);
ReactBootstrap.Dispatcher.off('sidebar:keychange', this.handleKeyChange);
},
render() {
var props = {
style: {
left: this.state.left,
visibility: this.state.visibility,
transition: 'none',
OTransition: 'none',
MsTransition: 'none',
MozTransition: 'none',
WebkitTransition: 'none'
},
...this.props,
className: classNames('sidebar', this.props.className)
};
return (
<div ref='sidebar' {...props} children={null}>
<div ref='innersidebar'>{this.props.children}</div>
</div>
);
}
});
export var SidebarNavItem = React.createClass({
timer: null,
mixins: [ History ],
contextTypes: {
location: React.PropTypes.object
},
propTypes: {
open: React.PropTypes.bool,
active: React.PropTypes.bool,
href: React.PropTypes.string,
autoHeight: React.PropTypes.bool
},
getInitialState() {
return {
open: this.props.open || false,
active: this.props.active || false,
toggleOpen: this.props.open || false,
dir: 'left',
opposite: false
};
},
emitOpen(open) {
var node = ReactDOM.findDOMNode(this.refs.node);
if(open) {
ReactBootstrap.Dispatcher.emit('sidebar:openstate', node, open);
} else {
ReactBootstrap.Dispatcher.emit('sidebar:openstate', node);
}
},
handleClick(e) {
if(!this.props.href) {
e.preventDefault();
e.stopPropagation();
}
if(this.props.hasOwnProperty('onClick')) {
this.props.onClick();
}
this.emitOpen();
},
collapse(node, cb) {
this.setState({
toggleOpen: false
}, () => {
var height = $(node).height();
$(node).css('height', height).animate({
height: '45px'
}, 125, 'easeInOutSine', () => {
$(node).css('height', '');
try {
this.setState({
open: false,
toggleOpen: false
}, () => {
if(cb) cb();
});
} catch(e) {}
});
});
},
expand(node, cb, disableAnimation) {
if(disableAnimation) {
$(node).css('height', '').addClass('open');
} else {
this.setState({
toggleOpen: true
}, () => {
var height = $(node).addClass('open').height();
$(node).removeClass('open');
$(node).css('height', '45px').animate({
height: height
}, 125, 'easeInOutSine', () => {
$(node).css('height', '');
try {
this.setState({
open: true
}, () => {
if(cb) cb();
});
} catch(e) {}
});
});
}
},
handleOpenState(child_node, open) {
clearTimeout(this.timer);
this.timer = setTimeout(() => {
if(this.props.children && this.isMounted()) {
var node = ReactDOM.findDOMNode(this.refs.node);
if(open) {
if($(node).find(child_node).length) {
this.setState({
open: true,
toggleOpen: true
});
this.expand(node, () => {
ReactBootstrap.Dispatcher.emit('sidebar:update');
}, true);
}
return;
}
if($(node).is(child_node)) {
if(this.state.open) {
this.collapse(node, () => {
ReactBootstrap.Dispatcher.emit('sidebar:update');
});
} else {
this.expand(node, () => {
ReactBootstrap.Dispatcher.emit('sidebar:update');
});
}
return;
}
if(!($(node).find(child_node).length)) {
if(this.state.open){
this.collapse(node);
}
}
}
}, 15);
},
handleLayoutDirChange(dir) {
this.setState({
dir: dir === 'ltr' ? 'left' : 'right',
opposite: dir === 'ltr' ? false : true
});
},
handleSearch(text, id) {
var node = $(ReactDOM.findDOMNode(this.refs.node));
if(id === this.props.SidebarNavID) {
if(node.text().toLowerCase().search(text.toLowerCase()) === -1) {
node.slideUp();
} else {
node.slideDown();
}
}
},
componentWillUnmount() {
ReactBootstrap.Dispatcher.off('layout:dir', this.handleLayoutDirChange);
ReactBootstrap.Dispatcher.off('sidebar:openstate', this.handleOpenState);
ReactBootstrap.Dispatcher.off('sidebar:search', this.handleSearch);
},
componentWillMount() {
ReactBootstrap.Dispatcher.on('layout:dir', this.handleLayoutDirChange);
ReactBootstrap.Dispatcher.on('sidebar:openstate', this.handleOpenState);
ReactBootstrap.Dispatcher.on('sidebar:search', this.handleSearch);
},
activateNavItem(props) {
var active = props.active || false;
var currentLocation = this.context.location.pathname;
if(!active && props.href) {
active = this.history.isActive(props.href) && (currentLocation == props.href);
}
$('.sidebar').css({
visibility: 'hidden'
});
if(active) {
global_delay = 0;
var node = ReactDOM.findDOMNode(this.refs.node);
var sidebarParent = $(node).parents('.sidebar');
$('.sidebar').css({
transition: 'none',
OTransition: 'none',
MsTransition: 'none',
MozTransition: 'none',
WebkitTransition: 'none',
visibility: 'hidden'
});
var i = $('#sidebar-container').find(sidebarParent).index();
$('.sidebar-control-btn').eq(i).click();
this.emitOpen(true);
sidebarParent.css('visibility', 'visible');
setTimeout(() => {
/*
Line bellow commented because of:
Warning: setState(...): Can only update a mounted or mounting component.
This usually means you called setState() on an unmounted component.
This is a no-op. Please check the code for the SidebarNavItem component.
*/
//this.setState({active: true});
var height = $(node).height();
var top = $(node).offset().top;
ReactBootstrap.Dispatcher.emit('sidebar:reposition', node, top, height);
sidebarParent.css('visibility', 'visible');
$('.sidebar').css({
transition: 'all 0.3s ease',
OTransition: 'all 0.3s ease',
MsTransition: 'all 0.3s ease',
MozTransition: 'all 0.3s ease',
WebkitTransition: 'all 0.3s ease'
});
}, 15);
$('.sidebar-control-btn').eq(i).click();
global_delay = 300;
} else {
this.setState({active: false});
}
},
componentWillReceiveProps(nextProps) {
this.activateNavItem(nextProps);
},
componentDidMount() {
this.activateNavItem(this.props);
},
render() {
var classes = classNames({
'open': this.state.open,
'active': this.state.active
});
var toggleClasses = classNames({
'toggle-button': true,
'open': this.state.toggleOpen,
'opposite': this.state.opposite
});
var icon=null, toggleButton = null;
if(this.props.children) {
toggleButton = <Icon className={toggleClasses.trim()} bundle='fontello' glyph={this.state.dir+'-open-3'} />;
}
if(this.props.glyph || this.props.bundle) {
icon = <Icon bundle={this.props.bundle} glyph={this.props.glyph} />;
}
var style = {height: this.props.autoHeight ? 'auto' : ''};
var props = {
name: null,
style: style,
tabIndex: '-1',
...this.props,
className: classes.trim()
};
var RouteLink = 'a';
var componentProps = {
name: null,
tabIndex: -1,
href: this.props.href || '',
onClick: this.handleClick,
style: style
};
if(this.props.hasOwnProperty('href') && this.props.href.length && this.props.href !== '#') {
RouteLink = Link;
componentProps.to = this.props.href;
delete componentProps.href;
}
return (
<li ref='node' {...props}>
<RouteLink {...componentProps}>
{icon}
<span className='name'>{this.props.name}</span>
{toggleButton}
</RouteLink>
{this.props.children}
</li>
);
}
});
export var SidebarNav = React.createClass({
getInitialState() {
return {
SidebarNavID: uuid.v4()
};
},
search(text) {
ReactBootstrap.Dispatcher.emit('sidebar:search', text, this.state.SidebarNavID);
},
render() {
var classes = classNames('sidebar-nav',
this.props.className);
var props = {
...this.props,
className: classes
};
var children = React.Children.map(this.props.children, (el) => {
return React.cloneElement(el, {
SidebarNavID: this.state.SidebarNavID
});
});
return (
<ul {...props} children={null} SidebarNavID={null}>
{children}
</ul>
);
}
});
export var SidebarBtn = React.createClass({
handleSidebarStateChange(props) {
if(props['data-id'] === 'sidebar-btn') {
ReactBootstrap.Dispatcher.emit('sidebar');
}
},
render() {
var classes = classNames('pull-left visible-xs-inline-block',
this.props.className);
var props = {
...this.props,
classes
};
return (
<NavContent {...props}>
<Nav onItemSelect={this.handleSidebarStateChange}>
<NavItem data-id='sidebar-btn' className='sidebar-btn' href='/'>
<Icon bundle='fontello' glyph='th-list-5' />
</NavItem>
</Nav>
</NavContent>
);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment