如何正确返回令牌并避免用户在令牌加载之前单击按钮的情况

问题描述 投票:0回答:1

//数据/API

   {"data":{"type":"token","attributes":{"token":"12345678908"}}}

这有效,我的令牌被发送回 api

  zE('messenger', 'loginUser', function (callback: any) {
    const token = query.data?.attributes?.token
    callback(token)
  })

我收到反馈说存在潜在的竞争条件,我应该先检查令牌是否已加载,所以我尝试了此操作,但 response.json() 没有向我发送令牌,而是

async function fetchZendeskToken() {
  const JWT_TOKEN_ENDPOINT = `${query.data?.attributes?.token}`

  const response = await fetch( JWT_TOKEN_ENDPOINT, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/vnd.api+json',
    },
  })
  
  console.log('response', response)

  if (!response.ok) {
    throw new Error(`Error fetching zendesk token`)
  }

  const data = await response.json()
  console.log('response', data)
}

响应的控制台日志:

Response {type: 'basic', url: 'http://localhost:8080/1234567890', redirected: false, status: 200, ok: true, …}

这现在不起作用:

zE('messenger', 'loginUser', function (callback: any) {
    callback(fetchZendeskToken());
  })
vue.js nuxt.js
1个回答
0
投票

所以基本上,您想要跟踪请求的

lifecycle
并查看它所在的位置,以便对 UI 进行知情更新,因此不允许用户单击按钮,除非请求已得到解决或拒绝。

这是

vue
中的一个简单用例:

<template>
  <div>
    <button @click="fetchZendeskToken" :disabled="isFetching">
      Fetch Zendesk Token
    </button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      isFetching: false,
    };
  },
  methods: {
    async fetchZendeskToken() {
      try {
        this.isFetching = true;

        const JWT_TOKEN_ENDPOINT = `${query.data?.attributes?.token}`;

        const response = await fetch(JWT_TOKEN_ENDPOINT, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/vnd.api+json',
          },
        });

        console.log('response', response);

        if (!response.ok) {
          throw new Error(`Error fetching zendesk token`);
        }

        const data = await response.json();
        console.log('response', data);

        // Here you can update the UI to display "Token fetched successfully", although, successful submits should be signified by a change of screen for better user experience. 

      } catch (error) {
        console.error('Error:', error);

        // Herem, you can update your UI to display some error message like "Error fetching token" or something similar.

      } finally {
        this.isFetching = false;
        // Once everything is done, you can set the isFetching variable to false.
      }
    },
  },
};
</script>
© www.soinside.com 2019 - 2024. All rights reserved.