I am building a web app using React/Redux and I have a problem coming up with a solution for something that should be simple: creating a new (nested) record and saving it to the server later.
I'm using normalizr to create a flat state tree. Basically my (relevant) state structure looks like this:
projects: {
as1234hhafs: {
_id: as1234hhafs
pages: [kljafsldasdf, asdfas8990],
...
}
},
pages: {
kljafsldasdf: {
_id: kljafsldasdf,
name: 'New page',
...
},
asdfas8990: {
_id: asdfas8990,
name: 'New page 2',
...
}
}
Each project has an array of subdocuments. What I want to do is to create a new page (subdocument) and edit it's data (and subdocuments) and save it to the server on click. But I'm at a loss at how to achieve this with the recommended redux/normalizr state structure.
How can I add a new record to the store if it doesn't have an ID yet? And how would I manage it once the response from the server assigns and ID to the record?
I hope my question is clear enough.
Two possible approaches:
Store unsaved entries in a separate part of the state, e.g. in an array which does not require an id. Move them to the set of persistent objects once they have been saved and you know the id. Merging the two sets of objects for the purpose of displaying them on the UI should not be too complicated.
Generate ids on the frontend Depending on what trade-offs you want to go with, this could be an incrementing number, a random UUID, or something completely different. You can then replace this temporary id with the permanent one once the record is saved.
Note that this is not an exhaustive list, and there is a multitude of other possible approaches. Just something to get you started.