繁体   English   中英

如何在 AWS DynamoDB 和 Amplify 中新建项目后更新项目

[英]How to update an item after being newly created in AWS DynamoDB and Amplify

我正在尝试在 Next.js 之上使用 AWS Amplify 更新 AWS Dynamo 中的查询。

我的场景很简单。

在页面加载时,如果存在用户并且该用户之前没有访问过页面,则将使用 SWR 使用设置值创建一个新的 object。

const fetchUserSite = async (owner, code) => {
  try {
    // Create site object if no site exists
    if (userData == null) {
      const siteInfo = {
        id: uuidv4(),
        code: parkCode,
        owner: user?.username,
        bookmarked: false,
        visited: false,
      }

      await API.graphql({
        query: createSite,
        variables: {input: siteInfo},
        authMode: 'AMAZON_COGNITO_USER_POOLS',
      })

      console.log(`${code} added for the first time`)
    }
    return userData || null
  } catch (err) {
    console.log('Site not added by user', data, err)
  }
}


 // Only call the fetchUserSite method if `user` exists
  const {data} = useSWR(user ? [user?.username, parkCode] : null, fetchUserSite)

目前,这有效。 object 已添加到具有上述属性的数据库中。 但是,当我单击一个按钮来更新这个新创建的 object 时,我收到path: null, locations: (1) […], message: "Variable 'input' has coerced Null value for NonNull type 'ID!'"

这是我在单击带有 onClick 处理程序“handleDBQuery”的按钮时更新 object 的调用。

const handleDBQuery = async () => {
  await API.graphql({
    query: updateSite,
    variables: {
      input: {
        id: data?.id,
        bookmarked: true,
        owner: user?.username,
      },
    },
    authMode: 'AMAZON_COGNITO_USER_POOLS',
  })
  console.log(`${name} Bookmarked`)
}

我的预感是 updateSite 查询不知道页面加载时的 createSite 查询。

简而言之,我如何在刚刚创建项目后更新它?

我查看了 master 分支的代码,并按照您的描述进行操作。 我发现这里的data?.id来自 state 变量,并且仅在调用createSite之前设置。 我建议您使用从createSite返回的数据再次尝试 setId

尝试这个

const fetchUserSite = async (owner, code) => {
  try {
    // Create site object if no site exists
    if (userData == null) {
      const siteInfo = {
        id: uuidv4(),
        code: parkCode,
        owner: user?.username,
        bookmarked: false,
        visited: false,
      }

      const { data: newData } = await API.graphql({
        query: createSite,
        variables: {input: siteInfo},
        authMode: 'AMAZON_COGNITO_USER_POOLS',
      });

      setId(newData.id); // <====== here (or setId(siteInfo.id))

      console.log(`${code} added for the first time`)
      return newData; // <======= and this, maybe? (you may have to modify the qraphql query to make it return the same item as in the listSite
    }
    return userData || null
  } catch (err) {
    console.log('Site not added by user', data, err)
  }
}

暂无
暂无

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

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