I am working on a Grocery List App with 2 models: Product and Grocery List. A Grocery List has many Products and a Product belongs to one Grocery List.
# schema.graphql
type Product @model
{
id: ID!
groceryList: GroceryList @connection(name: "GroceryListProducts")
name: String!
}
type GroceryList @model {
id: ID!
name: String!
products: [Product] @connection(name: "GroceryListProducts")
}
On DynamoDB, as far as I understand, the one-to-many relationship can be queried by using a global secondary index and won't be directly showing on the DynamoDb records:
DynamoDB Grocery List table:
╔═══════╦═════════╗
║ Id ║ Name ║
╠═══════╬═════════╣
║ L1 ║ List1 ║
║ L2 ║ List2 ║
║ L3 ║ List3 ║
╚═══════╩═════════╝
DynamoDB Product List table:
╔═════════╦═══════╦════════╗
║ Id ║ Name ║ PID* ║
╠═════════╬═══════╬════════╣
║ O1 ║ Orange║ L1 ║
║ O2 ║ Apple ║ L1 ║
║ O3 ║ Bacon ║ L2 ║
╚═════════╩═══════╩════════╝
*ProductGroceryListId
When I am adding a product and saving it on the DataStore as below:
const productSaved = await DataStore.save(
new Product(product)
)
await DataStore.save(
GroceryList.copyOf(currentList, updated => {
updated.products = [...updated.products, productSaved]
}))
The GroceryList instance on the datastore will be correctly showing the products children:
// GroceryList item showing on the browser DevTools, tab Application, IndexDB, amplify DataStore:
{
id: "L1"
name: "List1"
products: [
{id: "01", groceryList: {…}, name: "Orange"},
{id: "02", groceryList: {…}, name: "Apple"}
]
}
However, if I add the sync with the Cloud:
const subscription = DataStore.observe(Product).subscribe(msg => {
console.log(msg.model, msg.opType, msg.element);
})
The children will disappear from the GroceryList DataStore instance. How can I prevent it from happenning?
I would like to make sure I can use my app both online and offline.
Thank you in advance for your help!