Extracting a Config Module

Memisahkan api ke file config

Buat file baru di dalam src dengan nama config.json

{
    "apiEndpoint": "https://jsonplaceholder.typicode.com/posts"
}

App.js

import React, {Component} from "react";
import http from './Services/HttpService';
import config from "./config.json";
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(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 (
      <>
        <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;

dan buat folder baru di dalam src dengan nama Sevices, lalu buat file baru di dalam nya dengan nama HttpService.js

HttpService.js

import axios from 'axios';

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)
      alert('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?