Hello i'm trying to show a modal everytime when my api response with a error can you help me ? how can i do it ? i'm using react hooks
const restService = (path, responseType = 'json') => {
const apiUrl = `${CONFIG.API_HOST}/${path}`;
const create = async (body) => {
const config = {
responseType
};
try {
const response = await axios.post(apiUrl, body, config);
return response.data;
} catch (errors) {
//show modal
return {errors};
}
};
return {
find,
create,
update,
remove
};
};
Modal and settings to active the modal
You can achieve this by using React's Conditional Rendering.
Here's an example on how to achieve this: https://dev.to/kevhines/triggering-an-error-modal-in-react-3pm9
The component for the error message in the end of the article looks something like this:
import React from "react";
import {connect} from 'react-redux'
import clearError from '../actions/clearError'
class ErrorModal extends React.Component {
state = {
show: false
};
onClick = (e) => {
this.setState({
show: false
});
this.props.clearError()
};
componentDidUpdate(prevProps) {
if (this.props.error && !prevProps.error) {
this.setState({
show: true
});
}
}
render() {
if(!this.state.show){
return null;
}
return <div className="modal" id="modal">
<div>
<a href="#close" title="Close" className="close" onClick={this.onClick}>X</a>
<h2>Error Message</h2>
<p>{this.props.error}</p>
</div>
</div>
}
}
function mapStateToProps(state) {
return {error: state.error}
}
export default connect(mapStateToProps, {clearError})(ErrorModal)