'What is the proper way to pass a reactive pinia state as axios params?

I am trying to use two pinia stores for my axios params but when I send the axios request, the state is sent as a whole proxy object.

stores/product-filter.js

import { defineStore } from "pinia";

export const useProductFilterStore = defineStore("productFilter", {
  state: () => ({
    id: undefined,
    title: undefined,
    ...
  }),
});

stores/product-pagination.js

import { defineStore } from "pinia";

export const useProductPaginationStore = defineStore("productPagination", {
  state: () => ({
    pagination: {
      page: 1,
      rowsPerPage: 15,
      rowsNumber: false,
    },
  }),
});

stores/product.js

import { defineStore } from "pinia";

import { useProductFilterStore } from "./product-filter";
import { useProductPaginationStore } from "./product-pagination";

const paginationStore = useProductPaginationStore();
const filterStore = useProductFilterStore();

export const useProductStore = defineStore("product", {
  state: () => ({
    products: [],
  }),

  actions: {
    fetchProducts() {
      return axios.get(process.env.API_URL + "product", {
        params: {
          limit: paginationStore.pagination.rowsPerPage,
          page: paginationStore.pagination.page,
          filter: filterStore,
        },
      });
    },
  },
});

So when I fetchProducts I get the whole object like

limit: 15
page: 1
filter[$id]: productFilter
filter[_isOptionsAPI]: true
filter[router][currentRoute][__v_isShallow]: true
filter[router][currentRoute][dep][w]: 0
filter[router][currentRoute][dep][n]: 0
filter[router][currentRoute][__v_isRef]: true
filter[router][currentRoute][_rawValue][fullPath]: /product
filter[router][currentRoute][_rawValue][hash]: 
filter[router][currentRoute][_rawValue][name]: api.product.index
filter[router][currentRoute][_rawValue][path]: /product
filter[router][currentRoute][_rawValue][matched][][path]: /
filter[router][currentRoute][_rawValue][matched][][name]: api.default

Trying the following doesn't work either:

...
const { filter } = storeToRefs(filterStore);
...

params: {
  limit: paginationStore.pagination.rowsPerPage,
  page: paginationStore.pagination.page,
  filter: filterStore,
},

What is the best way to do this (reactively) ?



Solution 1:[1]

In stores/product.js, you are passing the entire store to Axios. It seems you want to pass just the state of the store, so try this:

fetchProducts() {
  return axios.get(process.env.API_URL + "product", {
    params: {
      limit: paginationStore.pagination.rowsPerPage,
      page: paginationStore.pagination.page,
      filter: filterStore.$state, // This
    },
  });
},

P.S. This was independently pointed out by Michal LevĂ˝ in a comment on your question.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1