using the composable pattern in vuejs version 3, <script setup lang="ts">, which each have data, loading and error, and wait for loading to finish on the first one before running the second compoable? in typescript

To use the composable pattern in Vue.js version 3 with <script setup lang="ts">, you can define a composable function that returns an object with reactive properties for loading, error, and data.

Then, to wait for loading to finish on the first composable before running the second one, you can use await and an isFinishedLoading variable to keep track of the loading state.

Here's an example:

index.ts
<template>
  <div>
    <p v-if="firstComp.loading">First comp is loading...</p>
    <p v-else-if="firstComp.error">{{ firstComp.error }}</p>
    <p v-else-if="secondComp.loading">Second comp is loading...</p>
    <p v-else-if="secondComp.error">{{ secondComp.error }}</p>
    <p v-else>{{ firstComp.data }} {{ secondComp.data }}</p>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'

const useFirstComp = async () => {
  const loading = ref(false)
  const error = ref('')
  const data = ref('')

  try {
    loading.value = true
    const response = await fetch('https://example.com/api/first')
    const json = await response.json()
    data.value = json.data
  } catch (e) {
    error.value = e.message
  } finally {
    loading.value = false
  }

  return { loading, error, data }
}

const useSecondComp = async (firstComp) => {
  const loading = ref(false)
  const error = ref('')
  const data = ref('')

  let isFinishedLoading = false

  try {
    loading.value = true
    await firstComp.loading
    isFinishedLoading = true

    const response = await fetch('https://example.com/api/second')
    const json = await response.json()
    data.value = json.data
  } catch (e) {
    error.value = e.message
  } finally {
    loading.value = false
  }

  return { loading, error, data }
}

const firstComp = useFirstComp()
const secondComp = useSecondComp(firstComp)
</script>
1402 chars
60 lines

In this example, the first composable function useFirstComp defines reactive properties for loading, error, and data. It uses the fetch API to make a request to an API endpoint and updates the reactive properties accordingly.

The second composable function useSecondComp takes firstComp as an argument and defines the same reactive properties. It sets loading to true and awaits firstComp.loading to wait for the first composable to finish loading.

Once loading is finished on the first composable, isFinishedLoading is set to true and the second composable continues with its logic, making a request to another API endpoint and updating its reactive properties.

Finally, in the template section, the reactive properties from both composables are displayed conditionally depending on their state.

related categories

gistlibby LogSnag