'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?
Solution 1:[1]
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>
);
}
Solution 2:[2]
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>
)
}
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Prajwal Kulkarni |
| Solution 2 |
