1.1.0 • Published 2 years ago

fetch-with-timeout-and-cache v1.1.0

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

fetch-with-timeout-and-cache

Extending fetch api to include timeouts, a client side cache and tries to avoid multiples requests and create resilients apps.

NPM

Table of Contents

Install

npm install --save fetch-with-timeout-and-cache

Usage

import React, { useState, useEffect } from 'react';
import fetchTC from 'fetch-with-timeout-and-cache'

interface Post {
  id: number;
  title: string;
  body: string;
}

function App() {
  const [posts, setPosts] = useState<Post[]>([]);

  useEffect(() => {
    fetchTC('https://jsonplaceholder.typicode.com/posts',
      {
        timeout: 1300,
      },
      {
        key: 'posts',
        ms: 30000,
      })
      .then(response => response.json())
      .then((data: Post[]) => setPosts(data));
  }, []);

  return (
    <div>
      <h1>Posts</h1>
      <ul>
        {posts.map(post => (
          <li key={post.id}>
            <h2>{post.title}</h2>
            <p>{post.body}</p>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default App;

Example with retry

import React, { useState, useEffect } from "react";
import fetchTC from "../../src/index";

interface Post {
  id: number;
  title: string;
  body: string;
}

function App() {
  const [posts, setPosts] = useState<Post[]>([]);

  useEffect(() => {
    fetchTC({
      resource: "https://mock.codes/500",
      cacheOptions: {
        key: "mocks",
        ms: 30000,
      },
      retryOptions: {
        delay: 2000,
        retries: 2,
      },
    })
      .then((response) => response.json())
      .then((data: Post[]) => setPosts(data));
  }, []);

  return (
    <div>
      <h1>Posts</h1>
      <ul>
        {posts.map((post) => (
          <li key={post.id}>
            <h2>{post.title}</h2>
            <p>{post.body}</p>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default App;

  return (
    <div>
      <h1>Posts</h1>
      <ul>
        {posts.map(post => (
          <li key={post.id}>
            <h2>{post.title}</h2>
            <p>{post.body}</p>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default App;

Properties

NameDescriptionDefault
resourceThis defines the resource that you wish to fetch
optionsAn object containing any custom settings that you want to apply to the request. Use the property timeout to define a custom timeoutundefined
cacheOptionsDefine the cache options if you want itundefined
retryOptionsDefine the retry options in case of internal server errosundefined

License

MIT © rafaelguinho

1.1.0

2 years ago

1.0.7

2 years ago

1.0.6

2 years ago

1.0.5

2 years ago

1.0.4

2 years ago

1.0.3

2 years ago

1.0.2

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago