src/util/sp/saveItem.js
/**
* Save or update an item.
*
* @example
* const obj = { id: 21, title: 'Mr.Beet' };
* saveItem('List', obj, (item) => {
* item.set_item('Id', obj.id);
* item.set_item('Title', obj.title);
* });
*
* @param {string} list Name of list
* @param {Object} item Object to save. Object.Id is used to fetch existing when updating
* @param {function(sp_item: Object):} assigner Function for assigning data to the SP list item
*
* @return {Promise<Object>} saved object.
*/
export default function saveItem(list, item, assigner) {
const { Id } = item;
return new Promise(function(resolve, reject) {
window.SP.SOD.executeFunc('sp.js', 'SP.ClientContext', () => {
const ctx = window.SP.ClientContext.get_current();
const path = `${window._spPageContextInfo.webAbsoluteUrl}/Lists/${list}`;
let sharepointItem;
if (Id) {
sharepointItem = ctx.get_web().getList(path).getItemById(Id);
}
else {
sharepointItem = ctx.get_web().getList(path).addItem(new window.SP.ListItemCreationInformation());
}
assigner(sharepointItem);
sharepointItem.update();
ctx.load(sharepointItem, 'Id');
ctx.executeQueryAsync(
function() {
const result = {...item};
result.Id = sharepointItem.get_id();
resolve(result);
},
function(sender, args){reject(sender, args);}
);
});
});
}