Learn how to retrieve data prior to rendering with Vue 3 and the composition api

Is there a way to fetch data from an API and populate my store (such as user info) before the entire page and components load? I have been struggling to find a solution.

I recently came across the beforeRouteEnter method that can be used with the options API, but what about using the composition API (especially with <script setup>)?

I attempted the following:

const router = useRouter()

router.beforeResolve(() => {
  // Fetch API and populate store
})

And also tried this:

router.beforeEach(() => {
  // Fetch API and populate store
})

Unfortunately, neither of these methods achieved the desired outcome.

Answer №1

Another question linked to this topic is: How can I make an API call within the created hook in Vue 3?

The recommended approach in the composition API is to simply include a

<script setup>
... imports...

const pizzas = ref([])

const GetPizzas = async () => {
  await api.get('pizza/pizzas/').then((response) => {
    pizzas.value = response.data
  })
}
GetPizzas()

</script>

This method makes sense since in the compositionAPI, the setup call acts as the "onLoad" or "onBeforeMount"

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

AddThis plugin in Wordpress is unresponsive when used with a theme that relies heavily

I've been struggling to properly set up the AddThis Wordpress plugin to display share buttons below each post in an AJAX theme. After inserting this code into the custom button field on the settings page: <div class="addthis_toolbox addthis_defa ...

Triggering a JavaScript function upon the alteration of a Dojo auto-complete widget's value

I'm encountering an issue with calling a javascript function when the value of a Dojo auto completer changes. Despite trying to call the function through the "onChange" attribute, it doesn't work as expected. Within the javascript function, my ...

Ways to eliminate an item from an array when the value of the object is not present

I am facing an issue with removing objects from an array that do not contain the data object. I have attempted to use the filter method but have not been successful. results.filter(obj => obj.data === undefined) results = [ {id: 1, location: 'a&a ...

How to modify the color of the placeholder text in a select dropdown using Material-ui

I have a material-ui select component that displays a dropdown menu of options for the user to choose from. The placeholder text, which currently reads "select option," appears in light grey to prompt the user to make a selection. However, I am concerned t ...

I encountered an issue stating, "The function `req.redirect` is not recognized."

Recently starting out with node development. Encountering the error below: TypeError: req.redirect is not a function at Post.create (/var/www/html/node_blog/index.js:40:7) at /var/www/html/node_blog/node_modules/mongoose/lib/utils.js:276:16 a ...

Using AngularJS and ServiceStack webservice, perform the "get('url')" operation

I'm completely new to AngularJS and I'm attempting to retrieve some JSON items from a webservice I quickly set up using ServiceStack. When I enter the URL in the browser, I can see the JSON object without any issues. However, for some reason Angu ...

Having trouble launching Cypress on my Mac - stating that it cannot find Cypress

Despite searching through multiple answers on S.O, none of them have solved my issue. To better explain my question, I've created a video. You can view it here Everything was working perfectly just yesterday, so what could have possibly gone wrong? ...

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. ...

Is the 404 page being utilized as a fallback for AJAX requests?

I am looking to create a one-page website that utilizes history.pushstate to modify the URL. My plan involves having only one HTML file for the site, which would be the 404 error page. This setup would redirect users to that page regardless of the URL they ...

Is it possible to transfer a URLFetchApp.fetch request from the Google Apps Script side to the JavaScript side?

My current task involves parsing an XML document tree upon clicking a button. The XML file is obtained using a lookup function that requires two values ("id" and "shipping") to be inserted into the appropriate URL. Then, the data retrieved is parsed using ...

Screening data entries

.js "rpsCommonWord": [ { "addressWeightPct": "60", "charSubstituteWeightPct": "15", "nameWeightPct": "40", "oIdNumber": "21", "shortWordMinLthWeightPct": "100", "substituteWeightPct": "5", ...

When the disk space is insufficient, the createWriteStream function will not trigger an error event if the file is not completely written

One challenge I'm encountering involves using createWriteStream: Imagine I have a large 100mb file that I want to write to another file on the disk. The available space on the disk is only 50mb. Here's my code snippet: const fs = require(&a ...

Using Vue along with bootstrap-vue: Ensuring only one list element is expanded in a list (v-for) at any given time

In my Vue project with bootstrap-vue, I am utilizing the b-collapse feature within a v-for loop for lists. While it is functioning correctly, I am struggling to automatically close expanded list elements when a new one is clicked. Here is my question: Ho ...

Extracting information from AJAX calls using a DataTable

When it comes to creating CRUD tables in school, I've always used scaffolding per page. However, I recently wanted to experiment with performing all operations without using Partial View. I decided to implement AJAX by following a tutorial on Everyth ...

Using AngularJS to bind models to a multidimensional array

As I am new to angular js, please bear with me. In my view, I have a grid of text input boxes that I would like to map to a 2D array in my controller or something similar in java script. The code in my view is as follows: <div ng-repeat="row in [1,2,3, ...

A guide to implementing the map function on Objects in Stencil

Passing data to a stencil component in index.html <app-root data="{<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b5d4d7d6f5d2d8d4dcd99bd6dad8">[email protected]</a>, <a href="/cdn-cgi/l/email-pro ...

What is the best way to access the element menu with element-ui?

I am looking for a way to programmatically open an element in my menu, but I haven't been able to find any information on how to do it. HTML <script src="//unpkg.com/vue/dist/vue.js"></script> <script src="//unpkg.com/<a hr ...

The JSON array retrieved from the $http.GET request is coming back as undefined, which is not expected

Presenting my code below: function gatherDataForGraph(unit, startTs, endTs, startState, endState){ points = []; console.log('/file/tsDataPoints/'+unit+"?startDate="+startTs+"&endDate="+endTs+"&startState="+startState+"&endState="+en ...

Coordinating a series of maneuvers

When it comes to coordinating multiple sequential actions in Redux, I find it a bit confusing. I have an application with a summary panel on the left and a CRUD panel on the right. My goal is to have the app automatically update the summary after a CRUD op ...

The filtering feature for array and model selection in Angular's UI-Select appears to be malfunctioning

Below is a Json structure: $scope.people = [ { name: 'Niraj'}, { name: 'Shivam'}, { name: 'Arun'}, { name: 'Mohit'}] There's also a variable, var array = "Niraj,Shivam";. My goal is to filter out the names fro ...