0.0.6 • Published 2 years ago

@fetch-suit/react-fetch-interceptor v0.0.6

Weekly downloads
-
License
UNLICENSED
Repository
github
Last release
2 years ago

React Fetch Interceptor

A very simple fetch interception solution for react

Installation

npm install @fetch-suit/fetch-interceptor @fetch-suit/react-fetch-interceptor

How To Use

Create a interceptor component

import React from 'react';
import { PropsWithChildren } from 'react';
import { FetchInterceptor, Fetch } from '@fetch-suit/react-fetch-interceptor';

async function bearerTokenInterceptor(request: Request, fetch: Fetch) {
  request.headers.append('Authorization', `Bearer fake.bearer.token`);
  return await fetch(request);
}

export const BearerTokenInterceptor = createInterceptorComponent(bearerTokenInterceptor);

// createInterceptorComponent equivalent to
export function BearerTokenInterceptor(props: PropsWithChildren<{}>) {
  return (
    <FetchInterceptor
      interceptors={ [bearerTokenInterceptor] }>
      {props.children}
    </FetchInterceptor>
  );
}
import React from "react";
import { useFetch } from '@fetch-suit/react-fetch-interceptor';
import { useEffect } from "react";
import { BearerTokenInterceptor } from './interceptors';

function FetchTest() {
  // use the intercepted fetch method instead of `window.fetch`
  const fetch = useFetch();

  useEffect(
    () => {
      const controller = new AbortController();
      fetch('/', { signal: controller.signal })
        .then(response => {})
        .catch(err => console.log(err));
      return () => controller.abort();
    },
    [],
  );

  return null;
}

export default function App() {
  return (
    <BearerTokenInterceptor>
      {/* apply bearer-token-interceptor */}
      <FetchTest />
    </BearerTokenInterceptor>
  );
}

Full example: click here

0.0.5

2 years ago

0.0.4

2 years ago

0.0.6

2 years ago

0.0.3

2 years ago

0.0.2

2 years ago

0.0.1

2 years ago