R
R
Raybul2022-02-21 18:22:55
React
Raybul, 2022-02-21 18:22:55

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)} />

but the problem is that if, after changing the status, I go to the page to another user, and then back to my own, then first the old status is displayed for a split second and then the new one, it won’t work)
How to solve the issue? thank you in advance )

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Raybul, 2022-02-21
@Raybul

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 question

Ask a Question

731 491 924 answers to any question