Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

115
Visualizações
Display an error message when API is not working

I have table data where I'm fetching that data through API. I need to display an error message on the user screen like something went wrong message

I tried the below code

const File history = () => {
   const [tableData, setTableData] = useState([]);
   const [isVisible, setIsVisible] = useState(true);
   const [errorMessage, setErrorMessage] = useState('');
   const getFileHistoryData = async() => {
    try {
      const response = await axios.get("api");
      const data = await response.data;
      if (data.length > 0) {
        setTableData(response.data);
      }
    } catch (e) {
      console.log(e.message)
    }
  };
  const renderErrorMessage = () => {
    return(
      <div>
         {errorMessage !- & (
             <h1>{'Something went wrong: + errorMessage}</h1>
         }}
      </div>
    )
}
  return (
      <div>
         {this.renderErrorMessage()}
         <MyTableComponent/>
      </div>  
     );
}

How do I display the error in the frontend render the message since it's a functional component?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

As I pointed out in the comment, you should change the function to store the error state, and change the rendering function to show that.

const File history = () => {
   const [tableData, setTableData] = useState([]);
   const [isVisible, setIsVisible] = useState(true);
   const [errorMessage, setErrorMessage] = useState('');
   const getFileHistoryData = async() => {
    try {
      const response = await axios.get("api");
      const data = await response.data;
      setErrorMessage('');
      if (data.length > 0) {
        setTableData(response.data);
      }
    } catch (e) {
      console.log(e.message)
      setErrorMessage(e.message);
    }
  };
  const renderErrorMessage = () => {
    return(
      <div>
         {errorMessage !== '' && (
             <h1>{'Something went wrong: + errorMessage}</h1>
         }}
      </div>
    )
}
  return (
      <div>
         {renderErrorMessage()}
         <MyTableComponent/>
      </div>  
     );
}
about 4 years ago · Juan Pablo Isaza Relatório

0

You could modify your code as such :

import React, { Component } from 'react',
import axios from 'axios',
import MyTableComponent from 'YOUR_PATH_TO_THIS_COMPONENT',

class File extends Component {
  state = {
    tableData : [],
    isVisible : true,
    errorMessage : '',
  }
  
  componentDidMount = () => {
    axios.get("api")
      .then(response => {
        const fileDataHistory = Object.values(response.data);
        if (data.length > 0) {
          this.setState({
            tableData:fileDataHistory,
          });
        }
      }
      .catch(error => {
        console.log(error);
        this.setState({
          errorMessage:error,
        });
  };
  
  renderErrorMessage = () => {
    return(
      <div>
         {this.state.errorMessage !== '' &&
             <h1>{'Something went wrong:' + this.state.errorMessage}</h1>
         }
      </div>
    )
  };
  
  render() {
    return (
      <div>
         {this.renderErrorMessage()}
         <MyTableComponent/>
      </div> 
    )
  }
};

about 4 years ago · Juan Pablo Isaza Relatório

0

You could use a state to store the error message when an error occurs and, use that value to display the error message. Instead of checking if the error message exists in the message rendering function, you could alternatively also use && operator to render the message conditionally.

const File history = () => {
   const [tableData, setTableData] = useState([]);
   const [isVisible, setIsVisible] = useState(true);
   const [errorMessage, setErrorMessage] = useState('');
   const getFileHistoryData = async() => {
    try {
      const response = await axios.get("api");
      const data = await response.data;
      setErrorMessage('');
      if (data.length > 0) {
        setTableData(response.data);
      }
    } catch (e) {
      console.log(e.message)
      setErrorMessage(e.message);
    }
  };
  const renderErrorMessage = () => {
    return(
      <div>
             <h1>{`Something went wrong: ${errorMessage}`}</h1>
      </div>
    )
}
  return (
      <div>
         {errorMessage.length && renderErrorMessage()}
         <MyTableComponent/>
      </div>  
     );
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda