我如何在出现由graphql useQuery返回的错误时关闭shopify北极星横幅? [英] How do I dismiss a shopify polaris banner on error returned with graphql useQuery?

查看:78
本文介绍了我如何在出现由graphql useQuery返回的错误时关闭shopify北极星横幅?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm very new to programming with react/javascript/node. I'm using Shopify CLI and generated a boilerplate app that uses react/next.js/apollo.

我不知道我是否针对自己想要的目标使用了正确的方法.我基本上是在尝试更新我的商人登录时应用程序的数据库数据库.

I don't know if I'm using the right approach for what I want to achieve. I'm basically trying to update my app's database of the merchants store information when they log in.

我的逻辑将是:

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

到目前为止,我只是在测试graphql方面.我创建了一个函数,该函数通过grapql从shopify检索数据.当我取回数据时,这似乎是可行的,如果我在graphql中添加错误,则会得到错误返回.

So far I'm just testing the graphql side. I created a function that retrieves the data from shopify via grapql. This seems to be working as I get the data back and if I add an error to the graphql I get the error return.

当他们遇到错误时,我想显示一个Shopify Polaris横幅.我已经尝试了多种方法从Google搜索中执行此操作,但没有找到正确的方法.

I want to display a shopify polaris banner when they get an error. I've tried various ways to do this from my google searches but haven't found the proper approach.

在下面的代码中,当出现错误时,我会看到横幅显示,但是由于它是通过返回功能 dismiss无效来呈现的.无法找到一种方法来显示错误,同时允许商家将其消除.

In the code below I get the banner display when there's an error however because it was rendered through the return of the function the dismiss doesn't work. I am unable to find a way to have it display the error while allowing it to be dismissed by the merchant.

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的各种课程的学习.感谢您的反馈.

I apologize for my lack of knowledge. I'm using this app with going through various courses on react/javascript to learn. I appreciate your feedback.

更新(以下评论):

我整理了一下,但是到目前为止这是index.js的代码

I cleaned it up a bit but here's the code so far for 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);
    },
    [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, 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>
    );
    
    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生成的页面已设置为创建这样的类:

Now the only thing is that the page generated with the Shopify CLI has it setup to create classes like this:

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中使用的功能是从github上shopify的react-app next.js示例复制而来的.在这种类型的应用中使用这可能是完全不合适的.

The above is just a test page from another page to test routes. It serves no purpose but you can see that it's using the class instead of a function like the app. The function used in index.js was copied from shopify's react-app next.js example on github. This might be completely inappropriate to use in this type of app.

export default function App() {

任何有关如何执行此操作以使它正确反应/javascript的指导表示赞赏.

Any guidance on how I should do this so that it's proper react/javascript is appreciated.

基本上,我的目标是只查询mongodb数据库中的商店数据,如果过时了要更新它,并显示北极星标语,如果GraphQL或数据库查询有错误,则将其取消.

知道您在做什么就很简单.哈哈

Simple when you know what you're doing. LOL

推荐答案

已更新:

嗨!对不起,我的最后一条评论我认为我不正确地理解您的问题.并感谢您更新问题.

UPDATED:

Hy! sorry for my last comment I think I don't understand your question properly. and thanks for updated question.

因此,有两种使用React创建组件的方法,一种是默认使用shopify的类组件,另一种是可以使用您想要的shopify的功能组件,但不限制您仅使用类组件,但是请记住功能组件具有它们自己的方法,例如用于状态和组件道具,而类组件具有其自己的方法.

so, there are two methods to create Component using React one is class component which shopify by default use, other is functional component you can use what you want shopify don't restrict you to use ONLY class component, But keep in mind functional component has their own methods like for state and component props and Class component has their own method.

要查询数据库或对shopify商店的api调用,您需要执行以下步骤.

for query your database or api call to your shopify store you need to follow the following steps.

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

  1. write a router in your server.js file in server folder like

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;
}

  • 在您的组件中,从获取方式调用上述路由器或api

  • In your component, call the above router or api from fetch like

    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
    );
    }
    

  • 希望如此对您有帮助.

    这篇关于我如何在出现由graphql useQuery返回的错误时关闭shopify北极星横幅?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆