nuxt32 fetch but only one request will be skipped

Asked 1 years ago, Updated 1 years ago, 344 views

nuxt ver:3.0.0-rc.11

In the following configuration, create a component that invokes the fetch method of the compatible and
After calling twice on pages, they call API requests only once

 components:composable define fetch method call
 compatible:callAPI fetch typescript
 pages —view page

composable/api.ts

export const useAnalyze=async(body:object):Promise<string>=>{
  const {data, pending, refresh, error} = wait useAsyncData(
    'key-analyze',
    ( ) = >
      $fetch('/analyze', {
        method: 'POST',
        body: body,
        asynconResponse({request,response}){
          console.log ('FETCH', request, response.status)
        }
      }),
    {
      initialCache:false
    }
  )
  console.log ('RESULT', data.value, error)

  return data.value
}

components/Parts.vue

<template>
  <div>
   {{ props.name}}:{{resultValue}}
  </div>
</template>
<script lang="ts" setup>

interface PartsProps {
  name —string
}
const prop=withDefaults (defineProps<PartsProps>(), {})

constresultValue=ref(')
onMounted(async()=>{
  const result=wait useAnalyze (props.name)
  resultValue.value=result
})
</script>

pages/view.vue

<template>
  <div>
   <Parts:name='value1'/>
   <Parts:name='value2'/>
  </div>
</template>

Looking at the information on the network, I have only made one request

Enter a description of the image here

log

console.log FETCH:one line output
console.log RESULT:two-line output

I would like you to skip the request twice, but if anyone knows how to solve this problem, please take care of it.

nuxtjs

2022-10-21 00:01

1 Answers

The useAsyncData key appears to be a fixed value.

key:a unique key to enable that data fetching can be properly de-duplicated across requests.
-- useAsyncData·Nuxt Composables

As you can see, the key is used to identify the request (for example, server and browser) and is responsible for avoiding multiple requests.The same goes for calls from multiple locations in the browser.If you want to use it for different requests, you'll need to set a unique key.

However, I don't know if useAsyncData is appropriate for this case.


2022-10-21 00:01

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.