简体   繁体   English

如何处理反应式异步获取输入字段错误?

[英]How do I handle reactive async fetch input field errors?

I have a store binded to an input box which re-fetches some data after every input, but when I either delete all the values in the input or set the input to outside of the bounds of what the fetch can retrieve, I get the following error and the bind seems to break and no longer responds to changes until I reload the page:我有一个绑定到输入框的商店,它在每次输入后重新获取一些数据,但是当我删除输入中的所有值或将输入设置为获取可以检索的范围之外时,我得到以下信息错误并且绑定似乎中断并且在我重新加载页面之前不再响应更改:

Uncaught (in promise) TypeError: Cannot read properties of null (reading 'newThing.property')
    at Object.update [as p] (index.svelte:85:40)
    at update (index.mjs:1093:36)
    at flush (index.mjs:1060:13)

index.svelte

<script>
  let Id
  export let thingStore = writable({})
  $: if (Id >= 0) {
          getNewThing(Id).then(newThing => thingStore.set(newThing))
          } else {
         getNewThing(0).then(newThing => thingStore.set(newThing))
          }
</script>

<input type="text" bind:value={Id}>
<div>
  {$thingStore.property}
</div>

getNewThing takes in values greater than 0 in order to receive a successful response. getNewThing接受大于 0 的值以接收成功的响应。

import { client } from "../lib/graphql-client";
import { gql } from "graphql-request";

const maxId = 9675

export const getNewThing = async (Id) => {
  if (Id === undefined) {
    Id = Math.floor(Math.random() * maxId)
  }
    try {
        const query = gql`
        query newThing{ property: "${Id}" }        
    `;
        const newThing = await client.request(query)
        return newThing
    } catch (error) {
        return{
            status:500,
            body: {error: 'There was an error.' }
        }
    }
}

The error object returned from an OOB input was causing a crash when the app went to read a non-existent property.当应用程序读取不存在的属性时,从 OOB 输入返回的错误 object 导致崩溃。 Modified my error object to include a .property property by default.修改了我的错误 object 以默认包含.property属性。

import { client } from "../lib/graphql-client";
import { gql } from "graphql-request";

const maxId = 9675

export const getNewThing = async (Id) => {
  if (Id === undefined) {
    Id = Math.floor(Math.random() * maxId)
  }
    try {
        const query = gql`
        query newThing{ property: "${Id}" }        
    `;
        const newThing = await client.request(query)
        return newThing
    } catch (error) {
        return{
            status:500,
            property: {error: 'There was an error.' }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM