簡體   English   中英

使用 Svelte 從 Javascript 中的 GraphQL 查詢訪問數據時出現問題

[英]Problems accessing data from a GraphQL query in Javascript with Svelte

Below I have my working function using a normal REST response that I want to try to convert into a GraphQL version, it fetches a JSON doc from my Phoenix Server and stores the object values from the JSON doc into an object. The problem is, here I can use await and then assign the new object values from the object within the JSON document, but using GraphQL I cannot access this data to assign it because there is no await function as its just a Query. (據我所知)

async function updatePageWithNewCompany(company){
        const res = await fetch(`http://localhost:4000/${company}`);
        profile = await res.json();
        profile = profile.companyProfile 
            DashboardStore.update(currentData => {
                return {
                    id: profile.id,
                    companyName: `${profile.company_name}`,
                    averageLength: profile.average_length,
                    } 
                })

最終,我問是否有辦法從 JavaScript 中的 GraphQL 查詢訪問和分配數據,以便在我的前端 Svelte 應用程序中顯示之前對其進行操作。

當前 GraphQL 查詢示例:

import { gql } from '@apollo/client'
import { client } from './apollo';
import { query, setClient } from "svelte-apollo";   

setClient(client)

const GET_COMPANY = gql`
      query{
        companyProfile(){
            companyName
            averageLength
            }
        }
    `;
const response = query(GET_COMPANY)
...

svelte-apollo查詢返回

一個隨着價值的到來而解決的承諾的精巧存儲

文檔中顯示的示例查詢中所述

因此,您可以直接在腳本部分利用該格式。 這是一個例子:

...
async function getCompany() {
  const companyStore = query(GET_COMPANY)
  const company = (await $companyStore).data.companyProfile
  return company  // format will be an object with keys { companyName, averageLength } according to your query
}
...

在旁注中,我建議始終在 GraphQL 查詢中獲取對象的id ,因為它通常是 Apollo 客戶端內部用於管理其緩存的密鑰(除非另有明確說明)。

我在@Thomas-Hennes 的幫助下找到了一個可行的解決方案

import { client } from '../apollo.js';
import { onMount } from "svelte";
import { gql } from '@apollo/client'

export const COMPANY_LIST = gql`
    query {
        listCompanies{
            companyName
        }
     }
  `;

async function listCompanies() {
    await client.query({query: COMPANY_LIST})
          .then(res => {
              companyList.update( currentData => 
              [...res.data.listCompanies.companyName])})
        };

onMount(() =>{
    listCompanies()
})

await 不喜歡被分配給變量或對其數據進行操作,因此我將其用作 promise 並操縱響應。 下面的鏈接幫助我找到了最后一塊拼圖。 https://docs.realm.io/sync/graphql-web-access/using-the-graphql-client

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM