I used aws-amplify for a very short time for my project. Recently, I'm facing a serious issue about data updating in DataStore in aws-amplify. After reading the docs from their official site I findout that, If I want to update data in DataStore it worked in Immutable way like this,
For creating data,
await DataStore.save(
new Post({
title: "My First Post",
rating: 10,
status: PostStatus.DRAFT
})
);
and for updating data ,
const original = await DataStore.query(Post, "123");
await DataStore.save(
Post.copyOf(original, updated => {
updated.title = `Any Title`;
})
);
there is no issue with creation but when I goes with update this line is a pain if you have more than 20 property in your object model. Because you have to write all those property and update with it .
updated.title = `Any Title`;
So, I want to update like this without writing all the property in manually,
const updatedTestResult = { ...this.testResult, ...this.testResultForm.value };
var result = await DataStore.save(TestResult.copyOf(this.testResult, updatedTestResult))
now it showing me this error,
TypeError: fn is not a function
at datastore.js:376:17
at produce (immer.esm.js:1:16034)
at Model.copyOf (datastore.js:375:32)
at test-result-form.component.ts:130:41
at Generator.next (<anonymous>)
at asyncGeneratorStep (asyncToGenerator.js:3:1)
at _next (asyncToGenerator.js:25:1)
at asyncToGenerator.js:32:1
at new ZoneAwarePromise (zone.js:1427:29)
at asyncToGenerator.js:21:1
or maybe there have another solution. Can you please me on that ?
I believe, copyOf function takes 2 parameters, 1st one is object and 2nd is callback. so, u can do something like this
await DataStore.save(
Post.copyOf(original, updated => {
...updated, ...this.testResultForm.value
})
);
Originally this question is answered in Github discussion. For updating a single property at a time, you could do the following:
async function updateTestResult(key, value) {
try {
const testResult = await DataStore.save(
TestResult.copyOf(originalTestResult, (updated) => {
updated[key] = value;
})
);
console.log("TestResult updated:", testResult);
} catch (error) {
console.error("Save failed:", error);
}
}
To update multiple properties at once, you could do the following:
async function updateTestResult(testResultForm) {
try {
const testResult = await DataStore.save(
TestResult.copyOf(originalTestResult, (updated) => {
for (const property in testResultForm) {
updated[property] = testResultForm[property];
}
})
);
console.log("TestResult updated:", testResult);
} catch (error) {
console.error("Save failed:", error);
}
}
if you want to see the original ansewer check out this link : https://github.com/aws-amplify/amplify-js/discussions/9984#discussioncomment-2959980