What is the best way to 'reorder' a connection in RelayJS?
In my user interface, I allow my user to 'swap' two items, but creating a mutation around that is a bit tricky.
What I'm doing right now is the naive way, namely using FIELDS_CHANGE
to change my node itself.
It works, but the problem is I can't seem to write an optimistic update for it. I am able to just pass a list of ids to my graphql server, but that doesn't work for the optimistic update because it expects the actual data.
So I guess I have to mock out my 'connection' interface, but unfortunately, it still doesn't work. I 'copied' my reordered nodes to getOptimisticResponse but it seems to be ignored. The data matches the actual server response. (ids simplified)
original:
{
item: {
edges: {
{cursor: 1, node: {id:2}}
{cursor: 2, node: {id:1}}
}
}
}
(doesn't do anything): optimistic reponse:
{
item: {
edges: {
node: {id:1}
node: {id:2}
}
}
}
server reponse:
{
item: {
edges: {
{cursor: 1, node: {id:1}}
{cursor: 2, node: {id:2}}
}
}
}
What gives? It's equivalent (except for the cursor), and even if I add the cursor in, it still doesn't work.
What am I doing wrong? Also is there an easier way to do mock my ids to a connection?
Also, as an aside, is there a way to get this data piecemeal? Right now, reordering two item re-requests the whole list because of my mutation config. I suppose I can do it with RANGE_ADD
, and RANGE_DELETE
to 'simulate a swap` but is there any easier way to do it?
Since you trigger a mutation in response to the user reordering the items, I assume, you store the position or order of the items on the server side. For what you're doing, one way of creating optimistic response can be using that position
or order
information. On the server side, an item needs to provide an additional field position
. On the client side, the items displayed are sorted by position
.
When the user swaps two items, in the optimistic response of your client-side mutation, you just need to swap the position
fields of those two items. The same applies on the server-side mutation.
The optimistic response code can be like:
getOptimisticResponse() {
return {
item1: {
id: this.props.item1.id,
position: this.props.item2.position,
},
item2: {
id: this.props.item2.id,
position: this.props.item1.position,
},
};
}