Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Add/Update with SP Http Client
try
{
let addorUpdateObj : any = {
AuthorId : customObj.user.id,
__metadata : {
'type': `SP.Data.CustomListItem`
}
}
console.log(`Sending object ${addorUpdateObj}`);
let body: string = JSON.stringify(addorUpdateObj);
let spHttpClient : SPHttpClient = context.spHttpClient;
let postURL: string = `${context.pageContext.web.absoluteUrl}/_api/web/lists/GetByTitle('${listTitle}')/Items` ;
let Action = 'POST';
if(customObj.id !== 0)
{
postURL = postURL + `('${customObj.id}')`;
Action = 'MERGE';
console.log(`update called ${postURL}`);
spHttpClient.post(postURL,
SPHttpClient.configurations.v1,
{
headers: {
'Accept': 'application/json;odata=nometadata',
'Content-type': 'application/json;odata=verbose',
'odata-version': '',
'IF-MATCH': '*',
'X-HTTP-Method': Action
},
body: body
}).then((response: SPHttpClientResponse) => {
console.log('Save result ' + response.ok);
if(response.ok)
{
resolve(true);
}
else
reject("Error while saving data");
});
}
else
{
console.log(`add called ${postURL}`);
spHttpClient.post(postURL,
SPHttpClient.configurations.v1,
{
headers: {
'Accept': 'application/json;odata=verbose',
'Content-type': 'application/json;odata=verbose',
'odata-version': ''
},
body: body
}).then((response: SPHttpClientResponse) => {
console.log('Save result ' + response.ok);
if(response.ok)
{
resolve(true);
}
else
reject("Error while saving data");
});
}
} catch(error)
{
console.log(error);
throw(error);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.