You can use SP PnP JS library to like/unlike list items/site pages.
Example:
import { sp, IItem } from "@pnp/sp/presets/all";
import "@pnp/sp/comments/item";
import { ILikeData, ILikedByInformation } from "@pnp/sp/comments";
// get a specific item by id.
let item: IItem = await sp.web.lists.getByTitle("My List").items.getById(1).get();
// like an item
await item.like();
// unlike an item
await item.unlike();
Documentation: @pnp/sp/comments and likes
Update:
Seems like you can also use old endpoints like:
/_api/Microsoft.Office.Server.ReputationModel.Reputation.SetLike(listID=@a1,itemID=@a2,like=@a3)
Source: Likes are not supported in this item
Also, you can try this approach of getting like count & liked by information from list item and then update list item with new like/unlike:
How to like/unlike resource via SharePoint REST API
Another Approach: Using JSOM in SPFx:
First of all, load JSOM modules in your web part as given here: Connect to SharePoint using the JavaScript Object Model (JSOM)
Then use below function to set like/unlike on list item:
export function likeUnlikeListItem(listName: string, itemId: number, isLike: boolean) {
Promise.resolve().then(
() => {
sp.web.lists
.getByTitle(listName)
.get()
.then(
(data) => {
Promise.resolve().then(
() => {
// eslint-disable-next-line
SP.SOD.registerSod(
"reputation.js",
"/_layouts/15/reputation.js",
);
// eslint-disable-next-line
SP.SOD.executeFunc(
"reputation.js",
"Microsoft.Office.Server.ReputationModel.Reputation",
() => {
// eslint-disable-next-line
const spContext = SP.ClientContext.get_current();
const listId = data.Id;
// eslint-disable-next-line
Microsoft.Office.Server.ReputationModel.Reputation.setLike(
spContext,
listId,
itemId,
isLike,
);
spContext.executeQueryAsync(
(data) => {
return true;
},
(error) => {
return false;
},
);
},
);
},
(error) => {
// error
console.log(error);
return false;
},
);
},
(error) => {
console.log(error);
return false;
},
);
},
(error) => {
console.log(error);
return false;
},
);
}
Usage:
To Like list item:
likeUnlikeListItem("My List", 1, true);
To Unlike list item:
likeUnlikeListItem("My List", 1, false);