Display Toast Notifications
npm i [email protected]
App.js
import React, {Component} from "react";
import { ToastContainer } from "react-toastify";
import http from './Services/HttpService';
import config from "./config.json";
import "react-toastify/dist/ReactToastify.css";
import './App.css';
class App extends Component {
state ={
posts: []
};
async componentDidMount() {
// pending > resolved (success) OR rejected (failure)
const { data : posts } = await http.get(config.apiEndpoint);
this.setState({ posts });
// console.log(posts)
}
handleAdd = async () => {
const obj = { title: "a", body: "b" };
const { data: post } = await http.post(config.apiEndpoint, obj);
// console.log(post)
const posts = [post, ...this.state.posts]
this.setState({ posts })
}
handleUpdate = async post => {
post.title = "UPDATED";
const { data } = await http.put(config.apiEndpoint + '/' + post.id, post);
const posts = [...this.state.posts];
const index = posts.indexOf(post);
posts[index] = {...post};
this.setState({ posts })
console.log(data)
}
handleDelete = async post => {
const originalPosts = this.state.posts;
const posts = this.state.posts.filter(p => p.id !== post.id);
this.setState({ posts });
try {
await http.delete("s" + config.apiEndpoint + "/" + post.id);
} catch (error) {
if (error.response && error.response.status === 404)
alert("This post has already been deleted.");
this.setState({ posts: originalPosts });
}
}
render() {
return (
<>
<ToastContainer />
<button className="btn btn-primary" onClick={this.handleAdd}>
Add
</button>
<table className="table">
<thead>
<tr>
<th>Title</th>
<th>Update</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{this.state.posts.map(post => (
<tr key={post.id}>
<td>{post.title}</td>
<td>
<button
className="btn btn-info btn-sm"
onClick={() => this.handleUpdate(post)}
>
Update
</button>
</td>
<td>
<button
className="btn btn-danger btn-sm"
onClick={() => this.handleDelete(post)}
>
Delete
</button>
</td>
</tr>
))}
</tbody>
</table>
</>
);
}
}
export default App;
HttpService.js
import axios from 'axios';
import { toast } from 'react-toastify';
axios.interceptors.response.use(null, error => {
const expectedError = error.response && error.response.status >= 400 && error.response.status < 500
if (!expectedError) {
console.log("Logging the error", error)
toast.error('Something failed while deleting a post!');
}
return Promise.reject(error);
})
export default {
get: axios.get,
post: axios.post,
put: axios.put,
delete: axios.delete
}
Last updated
Was this helpful?