Consuming REST APIs In React using ServerCall

Table of contents

No heading

No headings in the article.

If you are a React developer you will need to know to consume API. There are many ways of consuming API. In this article, you will be introduced to a better, faster, and more scalable way to consume API. APIs are what we can use to power our React applications with data. It consists of a set of data with mostly JSON, it is used to consume data on the client-side.

In React Applications there are many ways of consuming REST API in our Applications. which include fetch(), method, and Axios which is a promise-based HTTP client for the browser and Node.js. but I will be introducing Server Call.

My friend and I built Server Call on Axios to make API calls easier. It handles the try and catch, you don't need to rewrite API calls multiply times in our codebase Server Call. ServerCall has a peer library ServerCall CLI, The CLI makes it possible to generate typescript code for consuming REST API in your React codebase. the code handles data, error, and success in a very simple way.

HOW TO USE

Install npm install servercall --save

Create new folder src/servercall mkdir servercall

Install servercall cli npm install servercall-cli -g

Create store.ts touch servercall/store.ts

Copy the code below, edit it and follow the model to create your own store

import { ServerCallVerbs, ServerCallsType } from 'servercall';

export type ServerCallsKeyType = 'userExists' | 'sendShortCode' | 'getUser';

export const serverCalls: ServerCallsType<ServerCallsKeyType> ={
  userExists: { path: `/users/exists`, verb: ServerCallVerbs.Post, name: 'UserExists' },
  sendShortCode: { path: `/users/send/short-code`, verb: ServerCallVerbs.Post, name: 'SendShortCode' },
  getUser: { path: (args: { id: string }) => `/users/id/${args.id}`, verb: ServerCallVerbs.Get, name: 'GetUser' },
};

Create the initialization file (servercall/init.ts) touch servercall/init.ts

Copy the code below into (servercall/init.ts) and readjust it to fit your own use case

import { createServerCall } from 'servercall';

export const serverCall = createServerCall({
    baseUrl: 'http://localhost:9000',
    logger: console,
    defaultAuthSource: () => 'fake-auth',
    defaultResponseDataDept: (response: any) => response?.['data'],
    successFieldDept: (response: any) => response?.['data']?.['success'],
    // handleServerError: ()=>{}
  });

Server Call: npmjs.com/package/servercall Servercall-cli: npmjs.com/package/servercall-cli