Skip to content

escabora/gatsby-plugin-cache-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Version Downloads Total License CodeFactor

gatsby-plugin-cache-api

This plugin is used to cache any API.

Install

$ npm i gatsby-plugin-cache-api

or

$ yarn add gatsby-plugin-cache-api

How to use

import the function cacheApi in your gatsby-node.js.

const cacheApi = require('gatsby-plugin-cache-api');

exports.onPreInit = async () => {
  const api = await fetch('https://dog.ceo/api/breeds/list/all');
  const json = await api.json();

  const defineCache = {
    pathOutput: 'js/json',
    nameOutPath: 'breeds.json',
    file: json.message,
  };
  cacheApi(defineCache);
};

In your component do a fetch directly in your application

const MyComponent = () => {
  const [breeds, setBreeds] = useState([]);

  useEffect(()=> {
    const api = await fetch('./js/json/breeds.json'); //- cache
    const json = await api.json();
    const parseBreeds = Object.keys(json.message)
    setBreeds(parseBreeds);

  }, [])

  return <div> {breeds.map((breed)=> <p key={breed}>{breed}</p>)} </div>;
};

export default MyComponent;

On build Time

In the terminal you will see a success log with the path and name of the generated file

Shell Example

License

The code is available under the MIT License.

About

Plugin used for compile-time caching of any API.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published