How We Accidentally Created a Perfect Race Condition Example

import { reactive, computed } from “vue”;

const activeRequests = reactive([]);

export default function usePageRequests() {

const isLoading = computed(() => !!activeRequests.length);

const makeRequest = async (url) => {

// push the url to the activeRequests

const index = activeRequests.length;

activeRequests[index] = url;

const response = await fetch(url).catch((error) => alert(error)); // if failed remove the url from the activeRequests and alert error

const data = await response.json();

// remove the url from activeRequests

activeRequests.splice(index, 1);

return data;

};

return { isLoading, makeRequest };

}

The composable’s job is to make API requests and keep up with how many of them are actively in progress. The use case, was to show a single top level loading indicator while multiple nested components make separate requests. The top level loading indicator should only disappear once ALL requests were completed. Sure this could also be done with suspense, but the point of the lesson was to teach how to share reactive state (activeRequests) amongst multiple calls to the usePageRequests composable.

Leave a comment

Your email address will not be published. Required fields are marked *