Answer the question
In order to leave comments, you need to log in
How to get up-to-date data from the server when Apollo client is mutated?
Hello everyone, I just started to study the Apollo client and ran into some difficulty.
there is a list of users and there is a getuser request, when I click on a user, it executes useQuery into which I forward the userId, and for example, his first name, last name and status arrive, if I click "my page" then in useQuery I forward myId and my parameters arrive . What is the actual question:
if I change my own status, how can I display it on the page without restarting the page?
Options that I tried:
1. just after each change in a field, call refetch(). The problem is that if there is a lot of information, then when we change one status, it makes no sense to return the entire object.
2. create requests, for example, that return my personal information (getStatus, getName), etc., if I'm on someone else's page, then draw the information that is returned by the getUser request, and if I'm on my page, then draw what my requests return to me, then with mutation I call getStatus and it gets updated. Well here a problem that under each object it is necessary to write separate request.
3. store information in useState, for example:
const [newStatus, setNewStatus] = useState<string>('');
<div>{newStatus || data?.getUser.status}</div>
<Input type="text" value={newStatus} onChange={(e) => setNewStatus(e.target.value)} />
Answer the question
In order to leave comments, you need to log in
decision
const [editStatus, {data, loading, error}] = useMutation(EDIT_STATUS)
const submitNewStatus = () => {
editStatus({
variables: {
id: myId,
status: newStatus,
},
}).then((data) => {
client.writeFragment({
id: `User:${currentId}`,
fragment: gql`
fragment user on User {
status
}
`,
data: {
__typename: 'User',
status: data?.data.editStatus.status
}
})
})
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question