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

The JSON node fails to return a value after inserting data through an ajax request

I'm encountering an issue with a jQuery plugin that loads JSON data through an AJAX call and inserts it into an existing object. When I attempt to reference the newly inserted nodes, they show up as 'undefined', despite the data appearing co ...

What strategies can I implement to prevent the JavaScript CallStack from becoming overloaded?

The code snippet below outlines the functionality achieved through JavaScript (specifically for a node.js COMET application): A request is sent to the server and held until there is a response. Upon receiving a response, the data is processed, and anothe ...

What is the process for syncing ng-model with external data sources?

Here is a question that I have pondered: Let's consider the HTML code snippet below: <div id="container" ng-controller="Controller"> <my-tag ng-model="values"></my-tag> </div> Now, take a look at the controller defined a ...

What could be causing my Vue Router to not direct to my component?

Hey there, I'm fairly new to Vue and trying my best to navigate without diving into NPM. Please bear with me as I may ask some basic questions. Let's skip the template for now since I have a component set up and tested outside of routing: var T ...

Stopping the interval in Vue before the component is destroyed

I am currently facing an issue with a countdown timer implemented on a component. The timer functions properly, however, I want it to stop counting down once the user navigates away from the page where the component is located. I have attempted to use cl ...

Save the user input to a dedicated text file

I am working with a couple of select tags that generate an array. Previously, I was only logging the array to the console upon pressing the SUBMIT button, but now I want to save it to a separate text file. Here is my main.html code: <form method="POS ...

What is preventing me from retrieving these JSON values?

One of the functionalities on my website involves making an AJAX call to retrieve a member's profile information for editing purposes. The code snippet responsible for this operation is shown below: function loadProfileData() { var ...

Executing synchronous functions in NodeJS

I've been attempting to retrieve the number of records from a database using Node.js, but I'm running into an issue with synchronous requests. When I try to print the number inside the function, it works fine, but outside the function, it doesn&a ...

Using the Trigger Method in a Vue JS Component with Sibling Components

Seeking assistance once again for a VueJS2 project. Currently, I have a setup with a parent component, along with child1 and child2. The scenario is that the form in child1 needs to receive data from child2, which acts as a table. When a checkbox on a row ...

What is the method for identifying modules that rely on a specific module?

Is it possible to view all dependencies modules of a specific module, similar to this: npm-remote-ls <module-name> But how can we see the modules that depend on a particular module? Any help would be appreciated. Thank you. ...

Parsing of CSS and Javascript is disabled within iframes

Within my node.js application, I have configured an endpoint where I can load some parsed HTML code. This is achieved through the following code: app.get('/code', function (req, res) { res.setHeader('Content-Type', 'text/html& ...

The node module.exports in promise function may result in an undefined return value

When attempting to log the Promise in routes.js, it returns as undefined. However, if logged in queries.js, it works fine. What changes should be made to the promise in order to properly return a response to routes.js? In queries.js: const rsClient = req ...

The HTML file contains the complete version number of Firefox

If you're an expert in HTML, take a look at my expandable start page. I know there's room for improvement, and I'm seeking advice on automatically updating the Firefox browser version number in line 106 of the code snippet below. (Linux Mint ...

What is the best way to alternate between displaying HTML content with v-html and plain text in Vue.js?

I need a way to switch between v-html and plain text in Vue.js v2. Here's what I have so far: HTML <div id="app"> <h2 v-html="html ? text : undefined">{{html ? '' : text}}</h2> <button @click=&qu ...

What are the issues with using AJAX in conjunction with a for-loop?

I'm currently developing a small application that needs to create work schedules and calculate hours: . I've written the function kalkulacja() to calculate the inputs for each row and output the results through ajax. However, I'm facing an i ...

Creating a realistic typewriter effect by incorporating Code Block as the input

I am looking to add a special touch to my website by showcasing a code segment with the Typewriter effect. I want this code block not only displayed but also "typed" out when the page loads. Unfortunately, I have been unable to find a suitable solution s ...

Learn the process of flipping an element when a button is clicked!

I want to use the jquery flip.js library to flip an element. However, I only want the element to flip when I click on a specific flip button, and then flip back again when another button is clicked. Any suggestions on how to achieve this functionality? ...

Updating a component in Angular 4.3.1 from within an observable callback

My Project Journey I am currently immersing myself in learning Angular by working on a personal project: developing a game that involves routing, services, and more. One of the requirements is to hide the header on the landing page (route for '/&apos ...

Unable to invoke functions in the child window

In my Vue page, I have a script that opens a child window using the code snippet below: this.presentation = window.open( this.$router.resolve({name:'presentation'}).href, 'child window', 'width=auto,height=auto' ) ...

Transform the jQuery each method into vanilla JavaScript

I have a script that displays a dropdown in a select box. The current script I am using is as follows: jQuery.each( dslr, function( index, dslrgp) { var aslrp= dslrgp.aslrp; jQuery.each( aslrp, function(index2, pslrp) { var found = 0; ...