Using a function as a prop in Vue js to retrieve data from an API

I am facing an issue with a component that I want to decouple from the data fetching implementation. My goal is to be able to pass a data fetching callback as a prop.

The reason for this is so that I can easily mock the data fetching process 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) Usage of the component

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

Component's Prop type

  fetchProducts: {
    type: Function,
    required: true
  }

The issue arises when the incorrect prop type warning is displayed. The prop is being recognized as a Promise instead of a function, causing it to fail execution as fetchProducts is not considered a function.

Even after changing fetchProducts to return a number and removing the async behavior like this:

const fetchProducts = () => 9999

I still encounter errors stating that fetchProducts is a number, not a function! This indicates that even though I am passing a reference to the function, it is somehow being executed elsewhere.

Answer №1

After much trial and error, I finally got it to function by implementing a factory function.

export const retrieveItems = () => async (pageNum = 1, url = endpoints.fetchItems(1)) => {
  const response = await fetch(url);
  return await response.json();
}; 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Best practices for sorting a value while iterating through a map in ReactJS

Currently working on learning React JS by replicating a PHP website I previously developed. I've successfully used Axios to fetch data from the database and display it on the frontend. Now, I'm facing a challenge where I need to sort the results ...

Develop a custom function in Typescript that resolves and returns the values from multiple other functions

Is there a simple solution to my dilemma? I'm attempting to develop a function that gathers the outcomes of multiple functions into an array. TypeScript seems to be raising objections. How can I correctly modify this function? const func = (x:number, ...

The datepicker in Vuetify is failing to display any dates

My date picker modal expands correctly, but the dates are not showing up. https://i.stack.imgur.com/azC1w.png The datepicker functions perfectly on the Codepen demo, displaying the dates as expected. However, when I try to implement the same code in my ap ...

Saving the output of an AngularJS expression in an input field

Looking at the calculations below, I am currently evaluating an expression, {{ annualIncome * 4.5 }}, in one input and then re-evaluating the same expression in another input. Instead of saving the result and transferring it to the other input, I am repeat ...

Error message: Uncaught TypeError - The function 'send' is not recognized in the Ajax new Request

When I called my ajax function, I encountered the following error: Uncaught TypeError: ajaxGetData.send is not a function Here is my code: <button onclick="myFunc()" class="btn btn-default">Click</button> <div id="getRes"></div> ...

Unraveling complex JSON structures

JSON data is available on a specific URL: { "href":"http:\/\/api.rwlabs.org\/v1\/jobs?limit=10", "time":18, "links": { "self": { "href":"http:\/\/api.rwlabs.org\/v1\/jobs?offset=0&am ...

JavaScript Birthday Verification: Regular Expression Pattern

I am currently testing out JavaScript form validation. The information provided is not being sent to any database, it's just for format testing purposes. All the regex checks are functioning correctly apart from birth. It seems like there may be an i ...

Searching to loop through JSON within a Sequelize / Postgres database query in order to identify a corresponding value

Hello everyone, I'm new here so please bear with me. I'm currently working on a project using Sequelize with PostgresDB in Node and I need to search for a contact by email using findOrCreate function. The email entry is stored in JSON format (se ...

Set up Vue Awesome swiper when a user hovers over a product card

My goal is to have Vue Awesome Swiper initialize on product card hover, so that until the user hovers, only one image per product is loaded instead of multiple. HTML <div @mouseover="handleMouseOver" @mouseleave="handleMo ...

The issue of a jQuery slider malfunctioning when using an https URL on a Wordpress website

My WowSlider is experiencing issues on the main page of my Wordpress website with https. The images in the slider are stacked statically one after another. However, when the site is accessed with http, the slider works perfectly with the expected transitio ...

Leveraging AJAX and PHP for generating PDF files

My web application is designed to function in a specific way - the user fills out a form, and then using AJAX, the form data is sent to a PHP file that utilizes xpdf to generate a PDF. The goal is for the generated PDF to be easily downloadable on the HTML ...

Issue with React Router functionality not functioning

I am currently facing an issue with my react-router setup. You can find the code I am using by visiting this link - https://github.com/rocky-jaiswal/lehrer-node/tree/master/frontend Although it is a basic setup for react-router, I am experiencing difficu ...

Error: Exceeded the hook limit during rendering - reactjs problem

I keep encountering an issue when trying to retrieve main data using useSwr, where I call another function with axios and end up with an Uncaught Error: Rendered more hooks than during the previous render. I've attempted to troubleshoot this countless ...

Tips on attaching a suffix icon to a material-ui-pickers input box

Here is a snippet of my code: <Box p={6}> <Grid container spacing={2}> <Grid item xs={6}> <TimePicker autoOk label={t('checkIn')} value={time1} onChange={handlecheckIn} clearable /> </Grid> < ...

Can you provide a step-by-step guide on creating a JSONP Ajax request using only vanilla

// Performing an ajax request in jQuery $.ajax( { url : '', data: {}, dataType:'jsonp', jsonpCallback: 'callbackName', type: 'post' ,success:function (data) { console.log('ok'); }, ...

What is the Proper Way to Import Three.js Modules in a Vue Application?

My goal is to utilize three.js for displaying a gltf file. To achieve this, I need to import the GLTFLoader module from the three.js node package. As per the documentation, the correct way to import it is: import { GLTFLoader } from 'three/examples/ ...

Vue - Dynamically rendering a string as an element

Is there a way to generate a vue component using a string stored in my database? For instance, the string includes a message with a smiling emoji. I store it like this: Some text with Emoji: :santa::skin-tone-3:, and then replace all valid strings between ...

Attempting to implement usedispatch hook in combination with userefs, however, encountering issues with functionality

I've been exploring the Redux useDispatch hook lately. I created a simple app for taking notes in a todo list format. However, I am facing an issue with useDispatch as it's not working for me and I keep encountering this error: Module build faile ...

Retrieve the attributes of DOM elements following a successful AJAX request

Is there a way to retrieve the video duration using video.duration following my ajax video upload? Despite achieving ajax success, this function continues to return NaN. I have attempted methods such as $.when().then or $.when.done() but with no success. ...

Dilemma of interdependencies between Socket.io and requirejs

I am facing a challenge with my legacy express project that has two servers. The project includes two separate client files: requirejs.config({ baseUrl: '/js' , paths: { "jquery": "lib/jquery/jquery-2.1.1.min", "socket.io" : "lib/socket/ ...