import React, { Component } from 'react';
import InputForm from './InputForm';
import InputBotao from './InputBotao';
import PubSub from 'pubsub-js';
import $ from 'jquery';
class FormularioAutor extends Component{
constructor(){
super();
this.state ={nome:"",email:"",senha:""}
this.cadastrar = this.cadastrar.bind(this);
}
cadastrar(e){
e.preventDefault();
$.ajax({
url:'http://localhost:3000/autores',
contentType:'application/json',
dataType:'json',
type:'post',
data: JSON.stringify({nome:this.state.nome,email:this.state.email,senha:this.state.senha}),
success: function(novaListagem){
PubSub.publish('atualiza-lista-autores',novaListagem);
},
error: function(resposta){
console.log("erro");
}
});
}
render(){
return(
<div className="pure-form pure-form-aligned">
<form className="pure-form pure-form-aligned" method="post" onSubmit={this.cadastrar}>
<InputForm htmlFor="nome" label="Nome" id="nome" tipo="text" name="nome" value={this.state.nome} onChange={(e)=>{
this.setState({nome:e.target.value} )}}/>
<InputForm htmlFor="email" label="Email" id="email" tipo="email" name="email" value={this.state.email} onChange={(e)=>{
this.setState({email:e.target.value} )}}/>
<InputForm htmlFor="senha" label="Senha" id="senha" tipo="password" name="senha" value={this.state.senha} onChange={(e)=>{
this.setState({senha:e.target.value} )}}/>
<InputBotao tipo="submit" nome="Gravar"/>
</form>
</div>
)
}
}
class TabelaAutor extends Component{
render(){
return(
<div>
<table className="pure-table">
<thead>
<tr>
<th>Autor</th>
<th>Email</th>
<th>Senha</th>
</tr>
</thead>
<tbody>
{
this.props.lista.map((data)=>{
return(
<tr key={data.id}>
<td>{data.nome}</td>
<td>{data.email}</td>
<td>{data.senha}</td>
</tr>
)})
}
</tbody>
</table>
</div>
);
}
}
export default class AutorBox extends Component{
constructor(){
super();
this.state={lista:[]}
}
componentWillMount(){
$.ajax({
url:"http://localhost:3000/autores",
dataType: 'json',
success:function(resposta){
this.setState({lista:resposta});
}.bind(this)
}
)
PubSub.subscribe('atualiza-lista-autores', function(topico,novaLista){
this.setState({lista:novaLista});
}.bind(this));
}
render(){
return(
<div>
<div className="header">
<h1>Cadastro de Autores</h1>
</div>
<div className="content" id="content">
<FormularioAutor/>
<TabelaAutor lista={this.state.lista}/>
</div>
</div>
)
}
}