在SubscribeToMore中更新单个哈希而不是数组

时间:2017-08-10 07:20:54

标签: javascript reactjs meteor graphql react-apollo

如何更新单个哈希。当我尝试更改哈希值时,它不会改变。由于哈希是只读的,但是当我在数组中执行时,它可以工作。我在当前场景中只有哈希。

 subscribeToMore(
  {
   document: postUpdated,
   updateQuery: (previousResult, { subscriptionData }) => {

   if (subscriptionData.data.postUpdated) {

      console.log("------Updated hash------",subscriptionData.data.postUpdated);    

      previousResult.property.water_heater = subscriptionData.data.postUpdated.water_heater; 

    // readonly unable to assign

     return subscriptionData;
  }else{
    return previousResult;
    }

   },
  }
 )

但是使用此代码可以正常工作

subscribeToMore(
    {
      document: postUpdated,
      updateQuery: (previousResult, { subscriptionData }) => {
        previousResult.posts = previousResult.posts.map((post) => {
          if(post._id === subscriptionData.data.postUpdated._id) {
            return subscriptionData.data.postUpdated
          } else {
            return post
          }
        })
        return previousResult
      },
    }
  )

1 个答案:

答案 0 :(得分:0)

在第一个代码中,您正在改变previousResult.property,而在第二个代码中,您正在改变previousResult

我认为如果你这样做会有效。

subscribeToMore({
  document: postUpdated,
  updateQuery: (previousResult, { subscriptionData }) => {
    if (subscriptionData.data.postUpdated) {
      console.log("------Updated hash------", subscriptionData.data.postUpdated);    

      previousResult.property = {
        ...previousResult.property,
        water_heater = subscriptionData.data.postUpdated.water_heater; 
      }
    }
    return previousResult;
  },
})