Solucionado (ver solução)
Solucionado
(ver solução)
5
respostas

Deletar item de uma tabela

Como deletar um item de uma tabela e notificar o usuário da sua exclusão ocorrida com sucesso e atualizar a tabela?

5 respostas

Oi Luiz, tudo bem? Você precisa colocar um botão para cada linha, adicionar um evento no botão, implementar a funcionalidade no servidor(não está disponível no projeto atual do curso)... como isso vai ser fazer uma chamada ajax, você pega o retorno e altera o estado do componente. Lembre que quando você alterar o estado via setState, o render é chamado novamente o componente vai refletir o estado atual.

o botao ja tenho:

import React, { Component } from 'react';
import Dialog from 'react-toolbox/lib/dialog/Dialog';
import Button from 'react-toolbox/lib/button/Button';
import PubSub from 'pubsub-js';


export default  class DialogCustomizado extends Component{
  state = { active: false };
  token = localStorage.getItem('token-representante');
  emailRepresentanate = localStorage.getItem('email-represetante');
  host  =  JSON.parse(localStorage.getItem("servidores")).map(function(servidor){return servidor.url});

  handleToggle = () => {
    this.setState({active: !this.state.active});

  }

  excluir = () => {
    const requestInfo = {
            method:'DELETE',
            headers:{'Authorization': this.token}
        };
    fetch(this.host+"/pontua/"+this.props.url+"/"+parseInt(this.props.id), requestInfo)
    .then(response =>{
            if(response.ok){
                console.log(this.props.url+" removido(a) com sucesso");
                PubSub.subscribe("atualiza-lista",function(topico,promocoes){})
            }
     })
     .then(response =>{            

     })
     this.setState({active: !this.state.active});
  }


  actions = [
    {label: 'Excluir!',  onClick: this.excluir},
    {label: 'Cancelar!',  onClick: this.handleToggle}
  ];

  render () {
    return (
      <div>      
        <Button label={this.props.label} onClick={this.handleToggle} />
        <Dialog 
          actions={this.actions} 
          active={this.state.active} 
          title={this.props.title}
          type={this.props.type}
        >
          <p>{this.props.mensagem}</p>
        </Dialog>

      </div>
    );
  }

}

o listar ficou dessa forma

import React, { Component } from 'react';
import PubSub from 'pubsub-js';
import { Link  } from 'react-router-dom';
import '../assets/react-toolbox/theme.css';
import theme from '../assets/react-toolbox/theme.js';
import ThemeProvider from 'react-toolbox/lib/ThemeProvider';
//COMPONENTES
import DialogCustomizado from '../componentes/DialogCustomizado';

export default  class ListarPromocao extends Component{

   token = localStorage.getItem('token-representante');
   emailRepresentanate = localStorage.getItem('email-represetante');
   host  =  JSON.parse(localStorage.getItem("servidores")).map(function(servidor){return servidor.url}); 

   constructor() {
    super();    
    this.state = {lista : []};   
    this.state = {msg: ''}; 
    }
    componentWillMount(){
      console.log("excluida")
        PubSub.subscribe('atualiza-lista',function(topico,promocoes){
              this.setState({lista:promocoes});
        })

    }
    componentDidMount(){
      this.preencheLista();

    }

    preencheLista(){ 
      console.log("ENVIANDO: " + this.token);      
      const requestInfo = {
            method:'GET',
            dataType: 'json',
            headers: {'authorization': this.token},

        };
        console.log("ACESSANDO SERVIDOR: "+this.host+"/pontua/promocao");
        fetch(this.host+"/pontua/promocao", requestInfo)
        .then(response =>{
            if(response.status == 200 || response.status == 201){
              console.log("RESPOSTA DO SERVIDOR, 201, AUTOTIZADO");
              return response.json();
            }if(response.status == 401){
              console.log("NAO AUTORIZADO DIRECIONANDO PARA PAGINA DE LOGIN");
              this.props.history.push('/logout/representante');
            }else{
              console.log("NAO FOI POSSIVEL OBTER A(S) PROMOÇÃO(ÕES)");
                throw new Error('Não foi possivel obter promoções.');
            }
        })
        .then(promocoes =>{
          console.log(promocoes);
          if(promocoes.length > 0){
             this.setState({lista:promocoes});
             PubSub.subscribe('atualiza-lista',promocoes)

          }
        })
        .catch(error => {
            this.setState({msg:error.message});
        });


    }

    render(){

        if(this.state.lista){
            return(
                <div>
                    <h3>Promoções</h3>
                    <span>{this.state.msg}</span>
                      <TabelaPromocao lista={this.state.lista} />  
                </div>

            );
        }else{
          return(
            <div>
                <h3>Não existem promoções</h3>
                <Link to="/promocao/cadastrar"><button>Cadastrar Promocoa</button></Link>
            </div>

          );
        }
    }
}

class TabelaPromocao extends Component{
   render(){
     return(
              <table className="pure-table">
                        <thead>
                          <tr>
                            <th>Nome</th>
                            <th>Pontos</th>
                            <th>Inicio Vigencia</th>
                            <th>Fim Vigencia</th>
                            <th>Representante</th>
                            <th>Editar</th>
                            <th>Excluir</th>
                          </tr>
                        </thead>
                        <tbody>
                          {
                            this.props.lista.map(function(promocao){
                              return (
                                <tr key={promocao.id}>
                                  <td>{promocao.nome}</td>
                                  <td>{promocao.qtd_pontos}</td>
                                  <td>{promocao.inicio_vigencia}</td>
                                  <td>{promocao.final_vigencia}</td>
                                  <td>{promocao.representante_id.email}</td>
                                  <td>Editar</td>
                                  <td>
                                  <ThemeProvider  theme={theme}> 
                                    <DialogCustomizado
                                     label="Excluir"
                                     title={promocao.nome} 
                                     mensagem="Você gostaria de excluir?"
                                     id = {promocao.id}
                                     url = "promocao"     

                                    />
                                  </ThemeProvider>

                                  </td>

                                </tr>
                              );
                            })
                          }
                        </tbody>
                      </table>
     );
   }

}

estou tentando usar o Pubsub , mas não estou conseguindo. Pubsub é o caminho?

o pubsub parece um caminho sim, para comunicar com algum componente que você precisa exibir a mensagem. Eu não vi o evento linkado com o botão de excluir, mas posso ter me confundido.

entao em action eu chamo a funcao excluir, estou usando react toolbox

excluir = () => {
    const requestInfo = {
            method:'DELETE',
            headers:{'Authorization': this.token}
        };
    fetch(this.host+"/pontua/"+this.props.url+"/"+parseInt(this.props.id), requestInfo)
    .then(response =>{
            if(response.ok){
                console.log(this.props.url+" removido(a) com sucesso");
                PubSub.subscribe("atualiza-lista",function(topico,promocoes){})
            }
     })

     this.setState({active: !this.state.active});
  }


  actions = [
    {label: 'Excluir!',  onClick: this.excluir},
    {label: 'Cancelar!',  onClick: this.handleToggle}
  ];

se a exclusao for bem sucedida eu faço isso:

PubSub.subscribe("atualiza-lista",function(topico,promocoes){})
            }
     })

nao sei se ideia esta certa, eu me inscrevo no evento mas neste componente nao tenho a lista de promoção, gostaria de chamar no listaPromocao.js o componentDidMount, e pegar a lista do servidor novamente. Ficou mais claro. Obrigado pelas respostas professor.

solução!

no ListarPromocao.js ficou dessa maneira:

componentWillMount(){
          PubSub.subscribe('atualiza-lista',function(topico,promocoes){
          this.preencheLista();
        }.bind(this));

    }

em DialogExcluir.js ficou assim:

excluir = () => {
    const requestInfo = {
            method:'DELETE',
            headers:{'Authorization': this.token}
        };
    fetch(this.host+"/pontua/"+this.props.url+"/"+parseInt(this.props.id), requestInfo)
    .then(response =>{
            if(response.ok){
                console.log(this.props.url+" removido(a) com sucesso");
                PubSub.publish("atualiza-lista")
            }
     })

     this.setState({active: !this.state.active});
  }

dessa forma consigo excluir e fazer a requisicao novamente para o servidor

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software