Passing a function as a prop in Vue js to fetch data

Viewed 735

I have a component that I would like to be decoupled from the fetching data implementation. So that I can pass fetching data callback as a prop.

I would like to do that so that I can mock the fetching data in storybook.

Request.js

export const endpoints = {
  fetchProducts: page => `https://some-end-point-here?page=${page}`
};

export const fetchProducts = async (page = 1, endpoint = endpoints.fetchProducts(1)) => {
  const response = await fetch(endpoint);
  return await response.json();
}; 

(storybook) Where component is being used

import {fetchProducts} from "./request";
export const someCPM = ()=> ({
    components: {SomeCPM},
    props: {
        fetchProducts: {default: fetchProducts},
    },
    template: `<product-grid v-bind="$props"></product-grid>`
});

Prop type of component

  fetchProducts: {
    type: Function,
    required: true
  }

Problem is that I keep getting warned about the wrong prop type. Meaning it is getting Promise. Thus failing to execute as fetch products is not a function.

Even if a make fetchProducts to return number and remove async nature, like this:

const fetchProducts = () => 9999

I am then getting that fetch product is a number, not a function! This means that even tho I am passing a reference to the function somewhere somehow it is being executed.

1 Answers

I had to use factory function to make it work.

export const fetchProducts = () => async (page = 1, endpoint = endpoints.fetchProducts(1)) => {
  const response = await fetch(endpoint);
  return await response.json();
}; 
Related