lisaogren / axios-cache-adapter

Caching adapter for axios. Store request results in a configurable store to prevent unneeded network requests.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

POST request with form data

jkananen opened this issue · comments

I have a WordPress install, in which front end filters are implemented with POST requests with form data.

As a user may click the same filters repeatedly, I've tried to cache the responses, but cache.store.length() always returns 0 and response.request.excludedFromCache is true.

I've tried various things with key and invalidate but have had no success.

Is there a way to make this work?

getPosts(urlAjax, category) {
  const axios = require('axios').default;
  const { setupCache } = require('axios-cache-adapter');

  const cache = setupCache({
    maxAge: 15 * 60 * 1000,
    debug: true,
  });

  const api = axios.create({
    adapter: cache.adapter,
  });

  let formData = new FormData();
  formData.append('action', 'loadMore');
  formData.append('product_cat', category);

  return api({
    url: urlAjax,
    method: 'post',
    data: form_data,
  })
    .then((response) => {
      cache.store
        .length()
        .then((length) => {
          console.log(length);
        })
        .catch((error) => console.log(error));
      return response.data;
    })
    .catch((error) => console.log(error));
},

I spent a lot of time with a similar issue. The latest released version, 2.5.0, only support caching get requests. See here. If your method is not get it is automatically excluded from caching. It seems that in the 3.0.0 beta version support for caching post (and other methods) has been added.

Thanks for your response @ahartschen . I had read about that exact thing, but failed to realise v3 is still in beta.

It will take a little while until I can return to this task. In the meantime, any thoughts of 3.0.0-beta.0 are most welcome.

Hi, it might be helpful for someone, you can cache the POST request with data

"axios-cache-adapter": "^2.7.3",

here's how i did it,

created a store following this example https://www.npmjs.com/package/axios-cache-adapter#use-localforage-as-cache-store

return setup({
   baseURL: BASE_URL,

    // `axios-cache-adapter` options
    cache: {
      maxAge: 15 * 60 * 1000,
      store: forageStore,
      debug: false,
      clearOnStale: true,
      exclude: {
        methods: ["put", "patch", "delete"],
        query: false,
      },
      key: (req) => { // need key cause i had same request url but with different body data
        let serialized = JSON.stringify(req.params || "");
        return req.url + serialized;
      },
    },
  });

and here's how i use the store to fetch response

const api = await configure();
const response = await api({
    method: "POST",
    url: `/Event`,
    data: data,
    params: data.categoryId,
  });
return response;