Search code examples
vue.jsaxiosvuexnuxt.js

How to make loop in vuex action, axios loop


need help, i have this vuex action that get list of products by category id:

async GET_PRODUCTS({commit}, {cat}) {
    let products = []
    for (let i = 0; i < 2; i++) {
        let arr = await axios.get(
          `https://example.com/api/get-items.php`, {
            params: {
              cat,
              token: "0e94e09856a22496613b325473b7de8cb0a",
              p: i
            }
          }
        )
      console.log(arr);
      commit('SET_PRODUCTS', products.push(arr.data))
    }
    console.log(products);
    return products
  },

api gives only 100 products, I need to pass a parameter: p=0 its first 100 products, p=1 next 100, p=2 next 100, etc, how i can stop a loop when api returns less than 100 products in array? upd: now i have array of arrays, need to concat them in 1


Solution

  • Instead of pushing new sub-array to the master array, just concatenate them. And then break the cycle when you receive less than 100 items:

    async GET_PRODUCTS({commit}, {cat}) {
        let products = []
        for (let i = 0; true; i++) { // <--- loop forever
            let arr = await axios.get(
              `https://example.com/api/get-items.php`, {
                params: {
                  cat,
                  token: "0e94e09856a22496613b325473b7de8cb0a",
                  p: i
                }
              }
            )
          products = products.concat(arr.data) // <--- concatenate new array to the old one
          commit('SET_PRODUCTS', products)
          if (arr.data.length < 100) break // <--- exit the cycle
        }
        console.log(products);
        return products
      },