Cleaning Up Our JavaScript Code by Refactoring Them — Encapsulation
JavaScript is an easy to learn programming language. It’s easy to write programs that run and does something. However, it’s hard to write a piece of clean JavaScript code.
In this article, we’ll look at ways to refactor our code by encapsulating our API calls in their own React component, and use factory functions to provide polymorphism in our JavaScript code.
Encapsulate APIs in Our React Components
To decouple API calls from our components, we can call one API per component.
This way, if one API changes, it won’t break other components. It also keeps components simple because at most they use one API.
For instance, we can create components and use them as follows:
import React, { useState, useEffect } from "react";const Person = () => {
const [person, setPerson] = useState({});
const getData = async () => {
const res = await fetch("https://api.agify.io?name=michael");
const p = await res.json();
setPerson(p);
};
useEffect(() => {
getData();
}, []); return <p>{person.name}</p>;
};const Dog = () => {
const [dog, setDog] = useState({});
const getData = async () => {…