View real-time data in Vuejs 3 as it executes

I am currently working on a form that populates a table with data retrieved from a Laravel API. I am using Vue.js 3 and Composition API to build my entire application. When the button is clicked, I want the table to be filled with data from the form. The button has an @click function called

@click="searchRegisters()">
which triggers the searchRegister function. This function in turn calls an anonymous function within a composable that utilizes axios to perform a POST request and fetch data. Here is a snippet of the returned data:

{"data":[{"id":895,"name":"Aguilera Muriel Fatimas","address":"CALLE CALLEJAS, 8"

While my composable and function calls seem to be working fine, I am facing difficulties displaying the fetched data in my component named nAsignedCalls. To pass the data to this component, I use the searchRegister function that emits the data like this:

context.emit("registers", getRegisters(toRef(param_search,'param_search')))

In my setup(), I have defined a custom emit method as follows:

const emitMyEvent = (event) => emit('registers', event);

The getRegisters function within the composable returns the fetched data:

const getRegisters = async (param_search) => {
        var keys = Object.values(param_search);

        var formData = new FormData();
        formData.append("parameter", keys[0].parameter);
        formData.append("value", keys[0].value);
        let response = await axios.post('/api/listingApi/getRegister', formData, {'content-type': 'multipart/form-data'}) 
        registers.value = response.data.data
    } 

In the component nAsignedCalls, while defining it with export default defineComponent, I specify that it emits the 'registers' event:

emits: ['registers']

Furthermore, I return various functions and values related to the data handling:

return { 
       remove,
       searchId,
       searchName,
       searchPhone,
       edit,
       getResults,
       getPage,
       emitMyEvent,
       getRegisters,
       registers,
 }

To display the data in my template, I use a v-for loop to construct the table body:

<tbody>
            <template v-for="item of registers"> 
                <tr>
                    <td>{{ item.id }}</td>
                    ...
                    // Remaining code omitted for brevity
                </tr>
            </template>
        </tbody>

Despite successfully fetching the data in the network tab, I'm struggling to display it in the table or pass it correctly. I am relatively new to Vue.js 3 and still learning from extensive documentation.

UPDATE

I noticed that when assigning the result to my ref variable, a promise is obtained. So, I added the following then() function to handle this:

getRegisters(toRef(param_search,'param_search')).then(response => this.register_data = response)
console.log(this.register_data)

However, the console now shows a blank output. Any guidance or help will be greatly appreciated. Apologies for any language errors in my message.

Answer №1

If your goal is to simply fetch data and display it in a table, then there's no need for any additional events.

UPDATE

It doesn't matter where your data resides. Whether it's in a composable or Pinia store, you can access it easily.

Here's a simple example:

const { createApp, ref, onMounted } = Vue 

const useStore = () => {
  const posts = ref([])
  const getData = () => {
    posts.value = []
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then((response) => response.json())
      .then((data) =>  posts.value = data)
  }   
  return { posts, getData }
}

const Blog = {
  props: ['posts'],
  template: '#blog'
}

const App = {
  components: { Blog },
  setup() {    
    const { posts, getData } = useStore()    
    onMounted( () => getData());
    return { posts, getData }  
  }
}

const app = createApp(App)
app.mount('#app')
#app { line-height: 1.75; }
[v-cloak] { display: none; }
label { font-weight: bold; }
<div id="app" v-cloak>
<button @click="getData()">reload</button><br/>
<blog :posts="posts"></blog>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<script type="text/x-template" id="blog">
<div v-for="post in posts" :key="post.id">
  <label>Id:</label>&nbsp; {{post.id}}<br/>
  <label>Title:</label>&nbsp; {{post.title}}<br/>
  <label>Body:</label>&nbsp; {{post.body}}<br/>
  <hr/>
</div>
</script>

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

What steps do I need to take to ensure NextJS stores my edits in VSCode?

I have attempted various troubleshooting steps such as changing file extensions from .js to .jsx, turning on Prettier for formatting upon saving, setting it as the default formatter, reloading and restarting the editor. However, the issue with not being ...

Issue: ArrayBuffer failing to function properly in conjunction with Float64Array in NodeJS

Having some trouble with getting a Float64Array to work with an array buffer in Node. Here's what I've tried... var ab = new ArrayBuffer(buffer.length); var view = new Uint8Array(ab); console.log(view.length);//prints 3204 However, when I try ...

What is the best way to pause the display of dynamic search outcomes in React?

I am currently working on developing a dynamic search results workflow. While I have successfully managed to render the results without any issues, I am facing a challenge in toggling them off when all input is deleted from the search bar. When typing begi ...

Using Javascript libraries on a Chromebook: A comprehensive guide to getting started

Doing some coding on my chromebook and wondering if it's possible to download and utilize libraries such as jQuery. Would really appreciate any assistance with this! ...

Executing an Ajax SPARQL request in Firefox

I've been attempting to run an asynchronous Ajax sparql query on dbpedia using Firefox, but I encountered a strange issue that I can't seem to figure out. Surprisingly, the query works perfectly fine in Chrome, Edge, and Internet Explorer, but wh ...

AngularJS's support for html5mode on GitHub pages is now available

Is it feasible for GitHub pages to accommodate AngularJS in html5mode? I came across a source online suggesting that it can be done with a fallback page for 404 errors. However, this solution seems flawed as it may result in multiple 404 errors, which wou ...

Dynamic import of a SASS file in VueJS using a variable such as process.env

Is there a way to dynamically import a file using environment variables? I want to include a specific client's general theme SCSS to my app.vue (or main.ts) I'm thinking of something along the lines of: <style lang="sass"> @import"./th ...

Unable to retrieve the value of a specific property using _.map based on its property name

I'm currently facing a challenge with my app that utilizes MongoDB as its database. Specifically, I am having trouble extracting property values from array variables. Despite using a _.forEach method to confirm the presence of data, I encountered diff ...

Using Vue's forEach method in a computed property

I am currently working on a checkbox filter function that saves the value of clicked checkboxes in an array. However, I am encountering issues with updating the computed data as it is always returning undefined. The structure of the data: Casino { brand_ ...

Tips for altering attributes in a child element produced through v-for in VueJs 3

In my coding setup, the parent component generates child components using the v-for directive: <div class="planlist"> <ul id="planOl"> <PlanLego v-for="action in store.plan" :v-if="actio ...

Using TypeScript to import a Vue 2 component into a Vue 3 application

Recently, I embarked on a new project with Vue CLI and Vite, utilizing Vue version 3.3.4 alongside TypeScript. In the process, I attempted to incorporate the vue-concise-slider into one of my components. You can find it here: https://github.com/warpcgd/vu ...

Determining the quantity of items within a div using jQuery

Similar Question: Retrieve the count of elements inside parent div using jQuery Can you determine the total number of elements within a specific div? <div id=count"> <span></span> <span></span> <span></ ...

Difficulty displaying Vue components

Having inherited a troublesome codebase, I am facing an issue where the Vue components fail to load. The Vue framework seems to be mounting, but the components are not being displayed. This Laravel 5.7 application integrates blade templates with Vue elem ...

How to customize the preview grid design in material-ui-dropzone

I am working on a book form page in my React app which includes an option to upload a cover photo. I opted for material-ui-dropzone from https://yuvaleros.github.io/material-ui-dropzone/ and it's working well, but I encountered an issue with the previ ...

Getting the most out of Nexmo with multiple websocket connections

I have integrated the code provided by Nexmo (shown below) into my server. However, I am facing an issue where if two callers ping my server, the binary data from the second caller also streams into the same websocket endpoint, resulting in two binary st ...

Utilize user input to fetch data from an external API

Let's say there is a field for 'part number' input that is not enclosed in a form tag. Whenever a user enters a value, the onblur event or a button positioned next to the input field should trigger a query to an external site via its API and ...

What steps should I take to ensure my images load properly in my Vue application while utilizing webpack and vue-loader?

Having recently ventured into Vue, I find myself delving into some older code for a Vue application and facing the issue of images not loading onto the page. Despite validating that my component's asset paths are accurate as an extension within my cod ...

Nested SetTimeout function fails to execute

Attempting to implement a button that provides feedback for its actions, I am faced with a challenge in Angular. After sending a put request to the server, the button's state changes to show this action. Upon receiving a response, the button's st ...

Facing an ESIDIR error in NextJs, despite the fact that the code was sourced from the official documentation

For an upcoming interview, I decided to dive into learning Next.js by following the tutorial provided on Next.js official website. Everything was going smoothly until I reached this particular section that focused on implementing getStaticProps. Followin ...

What could be the reason for req.route displaying the previous route instead of

Question: const router = express.Router(); router .route('/:id') .delete( validate(messageValidator.deleteById), MessageController.deleteById, ) .get( validate(messageValidator.getById), MessageController.getById, ); ...