如何在 graphql useQuery 返回的错误中关闭 shopify polaris 横幅?

问题描述

我对使用 react/javascript/node 编程非常陌生。我正在使用 Shopify CLI 并生成一个使用 react/next.js/apollo 的样板应用。

我不知道我是否正在使用正确的方法来实现我想要实现的目标。我基本上是想在他们登录时更新我的​​应用程序数据库中的商家商店信息。

我的逻辑是:

  • 商家登录应用。
  • 我的应用将检查数据库并查看数据是否超过 24 小时。
  • 如果是,它会同步数据以确保应用是最新的。
  • 如果成功,我不需要显示任何内容,但我确实希望在 graphql 失败或数据库更新失败时显示错误

到目前为止,我只是在测试 graphql 方面。我创建了一个函数,通过 grapql 从 shopify 检索数据。这似乎在我取回数据时起作用,如果我向 graphql 添加错误,我会得到错误返回。

我想在出现错误显示 shopify polaris 横幅。我已经尝试了各种方法来通过我的谷歌搜索来做到这一点,但还没有找到合适的方法

在下面的代码中,当出现错误时,我得到了横幅显示,但是因为它是通过函数的返回呈现的dismiss 不起作用我是无法找到一种方法让它显示错误,同时允许商家将其关闭

function QueryShopifyStoreInfo() {
    const { loading,error,data } = useQuery(GET_STORE_informatION);
  
    if (loading) return null;
    if (error)  return  (
      <Layout.Section>
        <Banner title="Error Syncing with Shopify" status="critical" ondismiss={activeUpdateError}>
          <p>There was an error syncing your store data with Shopify.  We have been notified of the error and will investigate. This does not impact the functionality of the app. You can continue to use the app as normal.</p>
          <p>If you continue to receive this error,please send us a message.</p>
        </Banner>
      </Layout.Section>
    );
     
    return (
      null
    );
  }

我为我缺乏知识而道歉。我正在使用这个应用程序来学习关于 react/javascript 的各种课程。感谢您的反馈。

更新(以下评论):

我稍微清理了一下,但这是目前 index.js 的代码

import React,{useState,useCallback,Fragment} from 'react';
import gql from 'graphql-tag';
import { useQuery } from 'react-apollo';
import {
  Layout,Page,Card,Banner,} from '@shopify/polaris';


export default function App() {

  // Setup useStates
  const [active,setActive] = useState(false);
  const [UpdateErrorActive,setUpdateErrorActive] = useState(false);


  // Setup Variables
  //let UpdateErrorActive = false;  // Error Syncing Shopify Data

  // Setup Handles/useCallBacks
  
  
  // Setup Toggle Callbacks
  const toggleActive = useCallback(
    () => {
      setActive(!true);
    },[true],);

  

  // Toggle Update Error to Active
  const activeUpdateError = useCallback(
    () => {
      setUpdateErrorActive(!true);
    },);


 

  // Setup Breakcrumbs,Primary,Secondary Actions (if needed)


  // Setup Item Lists (choiceListItems in Polaris Sample)

  // Setup Changeable Texts based on status
    // const accountSectionDescription = connected
    //   ? 'disconnect your account from your Shopify store.'
    //   : 'Connect your account to your Shopify store.';


  // Setup Return Markups for display
  // const shopifyUpdateStatusMarkup = UpdateErrorActive ? (
  //   <Layout.Section><Banner title="Error Syncing with Shopify" status="critical" ondismiss={activeUpdateError}>
  //         <p>There was an error syncing your store data with Shopify.  We have been notified of the error and will investigate. This does not impact the functionality of the app. You can continue to use the app as normal.</p>
  //         <p>If you continue to receive this error,please send us a message.</p>
  //       </Banner></Layout.Section>
  // ) : (
  //   null
  // );

  
// Shopify GraphQL Query
const GET_STORE_informatION = gql`
query   {
  shop {
    id
    name
    email
    contactEmail
    description
    myshopifyDomain
    url
    plan{
      displayName
      partnerDevelopment 
    }
  }
}
`;

  // Functions

  // Retrieve Shopify Shop information and update database.
  function QueryShopifyStoreInfo() {

    const { loading,please send us a message.</p>
        </Banner>
      </Layout.Section>
    );
    
    console.log("Get Store information - data:")
    console.log(data);
  
    const shopID = data.shop.id;
    const shopName = data.shop.name;
    const email = data.shop.email;
    const contactEmail = data.shop.contactEmail;
    const description = data.shop.description;
    const myshopifyDomain = data.shop.myshopifyDomain;
    const url = data.shop.url;
    const plandisplayName = data.shop.plan.displayName;
    const partnerDevelopment = data.shop.plan.partnerDevelopment;
    console.log("partnerDevelopment",partnerDevelopment);

    return (
      null
    );
  }


  return (
    <Page
  fullWidth
  title="My Title"
  >
    <Layout>
      <QueryShopifyStoreInfo />
      {/* {shopifyUpdateStatusMarkup} */}
      <Layout.Section>
        <Card title="Online store dashboard" sectioned>
        <p>Lots of text here to go with this card.</p>
        </Card>
      </Layout.Section>
    </Layout>
      
  </Page>
  );
}

现在唯一的事情是使用 Shopify CLI 生成页面已设置为创建如下类:

class FindA extends React.Component {
  state = {
    discount: '10%',};

  

  render() {
    const { discount } = this.state;

    

    return (
      <Page>
        <Layout>
          <Layout.AnnotatedSection
            title="Test - Find A Page"
            description="Add a product to Sample App,it will automatically be discounted."
          >
            <Card sectioned>
            
              <Form onSubmit={this.handleSubmit}>
                <Formlayout>
                  <TextField
                    value={discount}
                    onChange={this.handleChange('discount')}
                    label="discount percentage"
                    type="discount"
                  />
                  <Stack distribution="trailing">
                    <Button primary submit>
                      Save
                    </Button>
                  </Stack>
                </Formlayout>
              </Form>
              
            </Card>
            
          </Layout.AnnotatedSection>
        </Layout>
      </Page>
    );
  }

  handleSubmit = () => {
    this.setState({
      discount: this.state.discount,});
    console.log('submission',this.state);
  };

  handleChange = (field) => {
    return (value) => this.setState({ [field]: value });
  };
}

export default FindA;

以上只是一个从另一个页面来测试路由的测试页面。它没有任何作用,但您可以看到它使用的是类而不是应用程序之类的函数。 index.js 中使用的函数是从shopify 在github 上的react-app next.js 示例中复制而来的。这可能完全不适合在此类应用中使用。

export default function App() {

任何有关我应该如何执行此操作以使其正确响应/javascript 的指导表示赞赏。

基本上,我的目标是查询商店数据的 mongodb 数据库,如果它已过时更新并显示 polaris 横幅,如果 GraphQL 或数据库查询出现错误,则该横幅可关闭

当您知道自己在做什么时很简单。哈哈

解决方法

更新:

嗨!抱歉我的最后一条评论我想我没有正确理解你的问题。 并感谢更新的问题。

因此,使用 React 创建组件有两种方法,一种是 shopify 默认使用的类组件,另一种是功能组件,您可以使用您想要的东西 shopify 不限制您只能使用类组件,但请记住功能组件有自己的方法,如状态和组件道具,类组件有自己的方法。


回答你的基本问题

要查询您的数据库或对您的 shopify 商店的 api 调用,您需要按照以下步骤操作。

  1. 在服务器文件夹中的 server.js 文件中编写一个路由器

    const koa_body = require('koa-body') //koa body parser install it if not
    router.get('/my-router',koa_body(),(ctx) => {
    //your query to db or API Call
    ctx.body = JSON.stringify({
    "flag": //query result or api result may be true or false
    })
    ctx.statusCode = 200;
    }
    
  2. 在你的组件中,从 fetch 中调用上面的路由器或 api

    function QueryShopifyStoreInfo() {
     const { loading,error,data } = useQuery(GET_STORE_INFORMATION);
    useEffect(() => {
      fetch('/my-router').
      then(resp => resp.json())
      .then(result => {
       console.log(data);
       error = data.flag;//this will update error according to flag return in body.
      })
    })
    
    if (loading) return null;
    if (error)  return  (
      <Layout.Section>
        <Banner title="Error Syncing with Shopify" status="critical" onDismiss={activeUpdateError}>
          <p>There was an error syncing your store data with Shopify.  We have been notified of the error and will investigate. This does not impact the functionality of the app. You can continue to use the app as normal.</p>
          <p>If you continue to receive this error,please send us a message.</p>
        </Banner>
      </Layout.Section>
    );
    
    console.log("Get Store Information - data:")
    console.log(data);
    
    const shopID = data.shop.id;
    const shopName = data.shop.name;
    const email = data.shop.email;
    const contactEmail = data.shop.contactEmail;
    const description = data.shop.description;
    const myshopifyDomain = data.shop.myshopifyDomain;
    const url = data.shop.url;
    const planDisplayName = data.shop.plan.displayName;
    const partnerDevelopment = data.shop.plan.partnerDevelopment;
    console.log("partnerDevelopment",partnerDevelopment);
    
    return (
      null
    );
    }
    

希望这对您有所帮助。