Skip to content

A simple approach to manage network requests in React. This helper listens and emits state changes (loading, success, failure) for each network request, eliminating the need to create redundant states every time. By centralizing state management for network requests, this solution simplifies the network request code and reduces repetition.

License

Notifications You must be signed in to change notification settings

nnieru/react-observable-network-helper

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

React Observable Network Helper

Problem: In React applications, managing state for each network request can become repetitive and inefficient. For every single network request, the developer must create a new state to track loading, success, or failure, leading to redundant code. This repetitive process complicates the application as the number of requests grows, making it harder to maintain and scale.

Challange: Find efficient way to manage state for a network requests without have a redundant code to manage the state.

Proposed Solution: Introducing a React Observable Network Helper – a simple approach to manage network requests in React. This helper listens and emits state changes (loading, success, failure) for each network request, eliminating the need to create redundant states every time. By centralizing state management for network requests, this solution simplifies the network request code and reduces repetition.

Overview:

overview

Flow:

flow

Installation

To install the library, use npm or yarn:

npm i react-observable-network-helper

Usage

Importing Package

import {
  HttpMethod,
  RequestFactory,
  useObservableHttpClient,
} from "react-observable-network-helper";

Creating Request

1. Create Axios Config

import { AxiosRequestConfig } from "axios";

export const axiosConfig: AxiosRequestConfig = {
  baseURL: "https://example.com",
};

2. Create Model and Mapper

export type PostModel = {
  userId: number;
  id: number;
  title: string;
  body: string;
};

export const mapToPostModel = (item: any): PostModel[] =>
  item.map((item: any) => ({
    userId: item.userId,
    id: item.id,
    title: item.title,
    body: item.body,
  }));

3. Create RequestFactory

const requestGetPost = RequestFactory<PostModel[]>({
  url: "/posts",
  mapper: (data) => mapToPostModel(data),
  httpMethod: HttpMethod.GET,
  config: axiosConfig,
  onErrorAction: (err) => {
    console.error(err);
  },
});

Using Request in React Component

const postRequest = useObservableHttpClient(requestGetPost);

Example Component

Here's a simple example of how to use the requests in a React component:

function App() {
  const postRequest = useObservableHttpClient(requestGetPost);

  return (
    <>
      <div>
        <button onClick={() => postRequest.fetchData()}>fetch api post</button>
      </div>

      <div>
        {postRequest.loading  && <div>loading...</div>}
        {postRequest.error  && <div>{postRequest.errorResponse?.message</div>}
        {postRequest.success && postRequest.data && postRequest.data.map((item) => (
          <div key={item.id}>
            <h3>{item.title}</h3>
            <p>{item.body}</p>
          </div>
        ))}
      </div>
    </>
  );
}

For the full code example you can go into the example directory example

I'm very happy to hear your feedback! Have a good day!

About

A simple approach to manage network requests in React. This helper listens and emits state changes (loading, success, failure) for each network request, eliminating the need to create redundant states every time. By centralizing state management for network requests, this solution simplifies the network request code and reduces repetition.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published