Reputation: 86260
I have my normalized store with lists and id mappings:
{
"byId": {
"images": {
"10984": {"id": "10984", "src": "/img.png"}
}
},
"myImages": [
"10948"
]
}
Now I want to create a new image, and add it to the list. The problem is that I don't have an id for it until I send it to the server. So I could generate a random id
"tempid19048": {"id": "tempid19048", src: "/img.png"}
"myImages": [
"10948",
"tempid19048"
]
And then I save it to the server and get an id back I dispatch an action. I may have tempid19048
used in multiple parts of the state.
What's a sane way to update everything with the new id? Am I approaching this all wrong?
Upvotes: 4
Views: 504
Reputation: 11585
Because Redux is really a client-side state manager, generally you just want to mirror the global state and thats it. As you know, unlike Flux/GraphQL, there isn't any functionality for caching, optimistic updates etc. My gut tells me building this would be difficult without compromising the pure simplicity that Redux is built on.
That said, I found redux-optimistic that mimicks Flux's optimistic updates for Redux. I've not used it, but it looks nice enough.
But with even with that said, I'd still highlight the simple solution of designing-out any need for temp ids / optimistic updates etc:
id
to the global stateUpvotes: 2
Reputation: 591
You can make IDs in "myImage"
as key-value pair.
"myImages": {
"10948": "10948",
"tempid19048": "tempid19048"
}
Now where ever you want to use you can use as
myImages["tempid19048"]
This will give you its current value as "tempid19048"
.
And if you need to change this tempId you need to change only the value, and key remains same.
"myImages": {
"10948": "10948",
"tempid19048": "newServerID"
}
Hence, irrespective of number of places you are using tempID
now you need to update in only one place.
Upvotes: 1