将useQuery返回的数据设置为状态

问题描述 投票:0回答:1

我一直在使用client.query从数据库中获取数据并使用useState设置状态。

这里是一个例子:

const [videos, setVideos] = useState([]); 

client.query({ query: GET_VIDEOS })
 .then(response => {
        setVideos(response.data.videos); 
})

但是,这不会在100%的时间内加载。通常,一段时间后第一次加载应用程序时,它不会加载。在这些情况下,我通常必须重新启动。

此问题使我想研究useQuery而不是client.query。

但是,文档中的示例仅显示了如何使用useQuery在组件中进行直接更改。

示例:

function Dogs({ onDogSelected }) {
  const { loading, error, data } = useQuery(GET_DOGS);

  if (loading) return 'Loading...';
  if (error) return `Error! ${error.message}`;

  return (
    <select name="dog" onChange={onDogSelected}>
      {data.dogs.map(dog => (
        <option key={dog.id} value={dog.breed}>
          {dog.breed}
        </option>
      ))}
    </select>
  );
}

但是,我现在不想更改组件。我宁愿查询数据,然后使用useState将查询的数据设置为状态。

我如何最好地做到这一点?我曾经想到的一个想法是创建一个返回null但查询数据的组件。它看起来像这样:

function Videos() {
  const { loading, error, data } = useQuery(GET_VIDEOS);

  if (loading) return 'Loading...';
  if (error) return `Error! ${error.message}`;

  setVideos(data); 

  return null;
}

我很想知道在这种情况下什么是最佳做法。

react-native expo apollo react-apollo
1个回答
0
投票

反应阿波罗的useQuery具有onCompleted作为其选项之一,因此您可以像使用它一样

const { loading, error } = useQuery(GET_VIDEOS, {
  onCompleted: (data) => setVideos(data)
});
© www.soinside.com 2019 - 2024. All rights reserved.