问题
I would like to execute 2 queries with hooks where the second query uses information retrieved in the first one. For example:
const { data, error, loading } = useQuery(GET_DOGS);
const result2 = useQuery(GET_BREEDS, { variables: { dogId: data[0].id } });
Right now I do it using some state and setting the skip
parameter on the second hook, however I figure there must be some easier solution which I might be overlooking?
回答1:
Hooks cannot be conditional, so you can't utilize an if
statement or an early return like we would do with a Query
component. For better or for worse, using the skip
parameter is the simplest solution:
const { data, error, loading } = useQuery(GET_DOGS);
const result2 = useQuery(GET_BREEDS, {
skip: !data,
variables: { dogId: data && data.dogs[0].id },
});
Incidentally, it's not all that different than how you would probably handle it if it were 2017 and we were still using HOCs and recompose.
来源:https://stackoverflow.com/questions/55837768/how-to-chain-usequery-hooks-using-react-apollo-hooks