Working with API in React.

This article was written to help you with basic knowledge working with API in react and as an individual review assignment of PPL CSUI 2021

this image is taken from memegenerator

API or Application Programming Interface is how your back-end and front-end in your software project connect each other. API provides interaction between one software and another, but not users.

When working with a web-based application, the most used API to be implemented is Representational state transfer API or RESTful API. It follows an architecture that uses predefined and stateless operations to access web resources. The web API requires the use of HTTP requests. There are four kinds of requests,

  • GET: Used to request data from the endpoint
  • POST: Sends data to an endpoint.
  • DELETE: Remove data from an endpoint.
  • PATCH: Update a record or data value at an endpoint.

Then how you implement API in your react project?

API Contracts

First of all, you need to define the endpoint and API method that provide the service that you need. All this thing is written in a document call API Contracts. The document provides use cases name, accessing method, Sucess Params, and Failed Params. This job needs to be discussed between the backend and software developer.

example of API Contracts

Defined The Reducers

Next, you need to define the method based on the API Contract method in your reducer action. Here is an example of the method implementation using Axios.

example of fetch method using Axios

Then you need to define the state in the reducer. Three scenarios need to be handled; PROCESSING, SUCESS, and FAILED state.

example of reducer implementation

In the example above, there are 3 states; FETCH_CLASS_GRADE, FETCH_CLASS_GRADE_SUCESS, and FETCH_CLASS_GRADE_FAILED.

  • FETCH_CLASS_GRADE is the initial API calling in the reducer, it signs that the programs call the API.
  • FETCH_CLASS_GRADE_SUCESS is the state that the API method is called successfully. You can save the return in a parameter, ie. gradeKelas.
  • FETCH_CLASS_GRADE_FAILED is the state that the API method call is failed. Here you need to save the error so you can do debug the error that occurs.

Implement the reducers

The next step is to implement the reducer that you have made into the web page. In this phase, you need to understand Props in React.

example of reducer mapping to the props

First, you need to set the props so it can load the output of the reducer call.

example of mapping reducer

Next, you need to map the reducer object into the props. Here you assigned the reducer to the props.

example of reducer call before the component rendered

Last, add the reducer in the componentDidMount() so the reducer will be called before the page is rendered.

End Words

Thank you for your enthusiasm to learn about API in React. I hope this article can help you with your project and assignment.

See you next time!

Computer Science Enthusiast