Reputation: 131
I have a query defined in backend server with graphql. I now want to fetch data from the server multiple times. Every time the variables will be different. As expected, the result data from the query should be different, too. However, it turned out that the data were the same. How can I request the query for multiple times with different variables? Here is my code snippet so far:
const [getMessage, { data, loading, subscribeToMore }]
= useLazyQuery(CHATBOX_QUERY, {
fetchPolicy: 'network-only'
});
useEffect(() => {
async function f() {
await getMessage({variables: { name1: "Bonny", name2: "Mary" }})
console.log(data)
await getMessage({variables: { name1: "Bonny", name2: "John" }})
console.log(data)
}
f()
}, [])
And here is my gql query defined in another file in frontend.
export const CHATBOX_QUERY = gql`
query chatbox($name1: String!, $name2: String!){
chatbox(name1: $name1, name2: $name2){
name
messages{
sender
body
}
}
}
`;
The result data of the query should have field "name" as {$name1+"_"+$name2}. As expected, the result of two printed data should have field "name" "Bonny_Mary" and "Bonny_John" respectively. But the actual result were "Bonny_John" for both printed data. This is quite strange... Does anyone know how to solve this?
Upvotes: 0
Views: 1740
Reputation: 7666
I think you need to embrace the hook paradigm more. Especially you effect looks very suspicious. I think you are using useLazyQuery
because you think it is the solution to your problem, but you don't seem to need it. useLazyQuery
is meant for situations, where you want to delay the execution of the query for some reason (e.g. because it is expensive and you are waiting for the results to be needed).
Either use two hooks if you know it is always two queries.
function MyComponent() {
const query1 = useQuery(CHATBOX_QUERY, {
fetchPolicy: 'network-only',
variables: { name1: "Bonny", name2: "Mary" }
});
const query2 = useQuery(CHATBOX_QUERY, {
fetchPolicy: 'network-only',
variables: { name1: "Bonny", name2: "John" }
});
return (
<div>
<div>{query1.data?.chatbox.name}</div>
<div>{query2.data?.chatbox.name}</div>
</div>
);
}
If you want to render a list of queries, create a component that uses its own hook and then render multiple components.
function MyComponent() {
const chats = ["Mary", "John"]
return (
<div>
{chats.map(chat => (
<Chat name1="Bonny" name2={chat} />
))}
</div>
);
}
function Chat(props) {
const query = useQuery(CHATBOX_QUERY, {
fetchPolicy: 'network-only',
variables: { name1: props.name1, name2: props.name2 }
});
return <div>{query.data?.chatbox.name}</div>;
}
Upvotes: 1