diff --git a/docs/pages/usage-examples.md b/docs/pages/usage-examples.md index ce0339d1..74642aac 100644 --- a/docs/pages/usage-examples.md +++ b/docs/pages/usage-examples.md @@ -1,4 +1,6 @@ -# Interceptor +# Usage and Examples + +There are some other examples in the [examples]([https://](https://github.com/arthurfiorette/axios-cache-interceptor/tree/main/examples), check them out! You can also make a PR to add some more. ## Applying diff --git a/examples/node/index.js b/examples/node/index.js new file mode 100644 index 00000000..0ee25c30 --- /dev/null +++ b/examples/node/index.js @@ -0,0 +1,49 @@ +/* eslint-disable */ + +const express = require('express'); +const app = express(); + +const Axios = require('axios'); +const { setupCache } = require('axios-cache-interceptor'); + +const api = setupCache( + Axios.create({ baseURL: 'https://jsonplaceholder.typicode.com/' }), + // 5 seconds + { ttl: 5 * 1000 } +); + +// Every time an api call reaches here, it will +// make another internal request and forward the response. +app.get('/', (req, res) => { + api.get('/users').then( + ({ data, cached, id }) => { + res.json({ + cached, + id: { + value: id, + deleteUrl: `/cache/${id}/delete`, + getUrl: `/cache/${id}/get` + }, + data + }); + }, + (error) => { + res.json({ error }); + } + ); +}); + +app.get('/cache/:id/delete', async (req, res) => { + await api.storage.remove(req.params.id); + res.send({ + status: 'Deleted!', + current: await api.storage.get(req.params.id) + }); +}); + +app.get('/cache/:id/get', async (req, res) => { + const cache = await api.storage.get(req.params.id); + res.json(cache); +}); + +app.listen(3000); \ No newline at end of file diff --git a/examples/react/app.js b/examples/react/app.js new file mode 100644 index 00000000..249e5d18 --- /dev/null +++ b/examples/react/app.js @@ -0,0 +1,36 @@ +/* eslint-disable */ + +import React, { useState } from 'react'; +import { useAxios } from './axios-context'; + +export const App = () => { + // You can use react context, as exemplified here + // but you can also just export the AxiosCacheInstance + // from a file and use it directly. Happy coding :) + const axios = useAxios(); + + const [{ data, error, loading }, setResponse] = useState({ + data: [], + loading: true, + error: null + }); + + axios.get('https://jsonplaceholder.typicode.com/users').then( + ({ data }) => setResponse({ data, loading: false, error: null }), + (error) => setResponse({ data: [], loading: false, error }) + ); + + if (loading) { + return