Accessing composable variables in Vue 3 without having to redefine refs from within a function

Currently, I am implementing a parent companyList component along with a reusable Table component and an useFetch composable in vue 3.2.

Prior to integrating the Table component, my code looked like this:

companyList

<script setup>
    import { computed } from 'vue';
    import useFetch from '@/composables/useFetch';
    import { formatEmail, formatPhone, formatEnterpriseNumber } from '@/utils/formatters';

    const { response, isFetching, error } = useFetch('get', '/companies');

    const companies = computed(() =>
        response.value?.companies?.map((company) => ({
            id: `#${company.id}`,
            name: `${company.legal_entity_type} ${company.business_name}`,
            enterprise_number: formatEnterpriseNumber(company.enterprise_number),
            email: formatEmail(company.email),
            phone: formatPhone(company.phone),
        }))
    );
</script>

Within the Table component that includes pagination, sorting, and search functionality, a watchEffect observes state changes and triggers an emit from the parent component, specifically getCompanies. Here's how it looks:

companyList

<script setup>
    const getCompanies = (search, sortKey, orderKey) => {
        const { response, isFetching, error } = useFetch('get', '/companies', {
            params: {
                keyword: search,
                sort_by: sortKey,
                order_by: orderKey,
            },
        });
    };

    const companies = computed(() =>
        response.value?.companies?.map((company) => ({
            id: `#${company.id}`,
            name: `${company.legal_entity_type} ${company.business_name}`,
            enterprise_number: formatEnterpriseNumber(company.enterprise_number),
            email: formatEmail(company.email),
            phone: formatPhone(company.phone),
        }))
    );
</script>

<template>
    <Spinner v-if="isFetching" size="medium" />
    <ErrorMessage v-else-if="error" showReload :description="error" />
    <NoDataMessage v-else-if="!companies || companies.length <= 0" />
    <div v-else>
        <Table :columns="tableColumns" :data="companies" @fetchData="getCompanies">
            <template v-slot:id="{ item }">
                <Badge>
                    {{ item.id }}
                </Badge>
            </template>
            <template v-slot:actions="{ item }">
                <router-link :to="{ name: 'clientDetails', params: { client_id: item.id } }" class="text-blue-500 lowercase"> {{ $tc('detail', 2) }} </router-link>
            </template>
        </Table>
    </div>
</template>

Question: I am looking for a way to extract the response, isFetching, and error values from the getCompanies function and utilize them inside the template tags without resorting to defining refs to retrieve them. Additionally, using different variable names makes the solution less optimal. Is there an alternative approach to the following workaround:

const local_response = ref(null);
const local_isFetching = ref(null);
const local_error = ref(null);

const getCompanies = (search, sortKey, orderKey) => {
    const { response, isFetching, error } = useFetch('get', '/companies', {
        params: {
            keyword: search,
            sort_by: sortKey,
            order_by: orderKey,
        },
    });

    local_response.value = response;
    local_isFetching.value = isFetching;
    local_error.value = error;
};

const companies = computed(() =>
    local_response.value?.companies?.map((company) => ({
        id: `#${company.id}`,
        name: `${company.legal_entity_type} ${company.business_name}`,
        enterprise_number: formatEnterpriseNumber(company.enterprise_number),
        email: formatEmail(company.email),
        phone: formatPhone(company.phone),
    }))
);

Answer №1

Delay the execution until you're ready with useFetch:

const {  go: fetchProducts, result, loading, errorMessage } =  useFetch('fetch', 
 '/products', {
    instant: false, // wait to execute until go is triggered
    details: {
        type: productType,
        category: productCategory,
        brand: productBrand,
    },
});

// fetchProducts, result, loading, and errorMessage will be accessible in the template 

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

Exploring ways to compare and update values in an array of objects using JavaScript

I have a situation where I need to compare the names and values of two arrays filled with objects. const array1 = [ { name: 'Sarah', value: null }, { name: 'Michael', value: null } ] const array2 = [ { na ...

I am experiencing an issue with Array.some not functioning properly within my React component, whereas Array.map is working

I am attempting to utilize Array.prototype.some() within my React component to check if a particular value exists in my array of objects. However, I keep encountering the error message data.some(...) is not a function. Interestingly, Array.prototype.map() ...

What steps can I take to ensure that my React child components will render successfully, even if a prop is absent

TLDR; Seeking solution to render child components in React even if a property of this.props is missing. My React app utilizes Yahoo's Fluxible and fetches data from a Wordpress site using WP REST API. Sometimes, the API may return incomplete data cau ...

Learn how to manipulate the DOM by dynamically creating elements and aligning them on the same line

Providing some context for my page: The section I have always contains a single input field. Below that, there is an "add" button which generates additional input fields. Since only one field is required on the screen, the following fields come with a "de ...

Executing the ES6 import syntax within a Node child process

After many attempts, I have come to the conclusion that I am ready to throw in the towel. My goal was to run a node es6 project that employs es6 import syntax; however, it seems that the child processes are not cooperating. The issue stems from the fact th ...

Ways to automatically style the child divs within a parent div

I'm trying to figure out how to float a parent div with child divs of different widths and heights while maximizing the use of space and not being affected by absolutely positioned elements. For reference, here's an example: http://jsfiddle.net ...

React-Image-Annotate encountered an issue: SyntaxError - The import statement cannot be used outside a module

Encountering an issue while trying to set up react-image-annotate. Here is the problem I am facing initially: https://i.stack.imgur.com/XgYPd.png This is how I have implemented it: import React from 'react' import ReactImageAnnotate from ' ...

Rendering JSON Data in JavaScript using Table Pagination

Currently, I am working on rendering JSON data from a URL onto a table. My challenge is to display only 10 rows per page and I'm seeking guidance on how to achieve this. Below is the code snippet that I am using for rendering the data: const url = " ...

Tips for swapping out a new line character in JavaScript

Hello! I'm currently facing a challenge with some code. I have a function designed to replace specific HTML character values, such as tabs or new lines. However, it's not functioning as expected. var replaceHTMLCharacters = function(text){ tex ...

A comprehensive guide on iterating through an array in JavaScript

Currently, I am facing an issue while trying to iterate over an array of Objects in React that have been fetched from Django. The object is stored as an array, but when attempting to map it, I encounter a typeerror stating "cannot read property map of unde ...

What is the purpose of including a function in an AngularJS dependency array?

When it comes to injecting dependencies, the process involves the following steps: inject(["$scope", "$compile", function ($scope, $compile) { ... }]); The syntax used here may seem strange. Placing the function inside the array might appear counter-in ...

Using the tensorflow library with vite

Greetings and apologies for any inconvenience caused by my relatively trivial inquiries. I am currently navigating the introductory stages of delving into front-end development. Presently, I have initiated a hello-world vite app, which came to life throug ...

Utilizing Google APIs to split a route among multiple locations

I am facing a scenario where A laundry company operates from one shop location. The laundry company has 3 trucks available (n trucks). The laundry company needs to deliver washed clothes to multiple locations (n locations). https://i.sstatic.net/ULup8.pn ...

Obtaining the 3D point coordinates from UV coordinates on a 3D plane object using Three.js

I am in the process of creating basic data visualizations using Three.js as my tool of choice. I have a series of PlaneGeometry meshes to which I am applying a transparent texture dynamically generated with red squares drawn at varying opacity levels. My g ...

Is it possible to implement a single lightbox modal that can display multiple images?

I am looking to create a fullscreen lightbox modal for multiple images, but I have been facing issues with finding the right solution. Most lightbox modals out there rely on jQuery and older versions of Bootstrap. Here is what I have tried so far: HTML: ...

Using a vanilla JS object as a prop for a child component

I have created a custom Message class in my application to handle incoming messages, which is defined in message.js. Within message.js, I've implemented two classes: Message and EventEmit. The render function in my Message class requires passing an E ...

Establishing the default selection and deactivating the notification

I've been struggling for a while to make this function properly. My knowledge of jquery and javascript is limited, so I'm facing some challenges. What I'm aiming to do is to have a default option selected from the drop-down menu when the but ...

What is the method for determining the data type of a column in an Excel sheet that has been

Currently, I am utilizing the XLSX npm library to convert an Excel sheet into JSON format. However, all of the retrieved data is currently being returned as strings. To see a demo of the XLSX read process, you can visit this Stackblitz demo Is there a w ...

Combine div elements with identical class

Is there a way to utilize jQuery in order to enclose groups of elements with the same class within a div? I have been searching for a solution, but haven't found one yet. Here's an example of the HTML: <div class="view-content"> < ...

Transforming an HTML Attribute into a JavaScript Object

I'm encountering an issue with converting an HTML-data attribute into a JavaScript Object. Here is my approach: The data Attribute appears as: <a id="stringObj" data-string="{'Foo':'Bar'}">Some A-Tag</a> In JavaScri ...