I created a LWC component that displays a ContentDocument with a file preview option (using lightning navigition, NavigationMixin. I want to be able to refresh the component if the user clicks on the preview option and makes any changes to the ContentDocument (details or deletes) or adds a new ContentVersion. It this possible to hook into the service for this? Is this something that has to be accomplished with a Platform Event?
2 Answers
Platform event will definitely help you with your problem. You can fire the event from Content Object Trigger and listen the event in your component. This will let you do what you want to do on change in content object.
-
Thanks. For now I setup a Platform Event, but it doesn't consistently work. I'm getting "403 Unknown Client" errors intermittently in the LWC when I attempt to subscribe to the event. When it does subscribe and I receive the message it works fine: I opened up a case with Salesforce in the interim in regards to the 403 errors. Commented Nov 13, 2020 at 18:42
I ended up using a Platform Event and setting up the channel in the LWC component to refresh Apex when new message is received. Also added a refresh button to do the same.
Small excerpt of the code.
// For refreshing Apex
result;
channelName = '/event/Some_Event__e';
connectedCallback() {
this.handleSubscribe();
}
disconnectedCallback() {
this.handleUnsubscribe();
}
@wire(getFiles, { recordId: '$recordId' })
wireGetReportFiles(result) {
this.result = result;
const { data, error } = result;
if (data) {
// code not displayed
} else if (error) {
console.error(error);
this.dispatchEvent(
new ShowToastEvent({
title: 'Error retrieving files',
message: reduceErrors(error).join(', '),
variant: 'error'
})
);
}
}
handleSubscribe() {
// Callback invoked whenever a new event message is received
const messageCallback = (response) => {
console.log('New message received: ', JSON.stringify(response));
// This will refresh the UI
return refreshApex(this.result);
};
// Check if Emp is enabled
isEmpEnabled().then((isEnabled) => {
if (isEnabled) {
console.log('Emp Enabled');
// Invoke subscribe method of empApi. Pass reference to messageCallback
subscribe(this.channelName, -1, messageCallback).then(
(response) => {
// Response contains the subscription information on subscribe call
console.log(
'Subscription request sent to: ',
JSON.stringify(response.channel)
);
this.subscription = response;
}
);
} else {
console.error('Emp is not enabled');
}
});
}
handleUnsubscribe() {
// Invoke unsubscribe method of empApi
unsubscribe(this.subscription, (response) => {
console.log('unsubscribe() response: ', JSON.stringify(response));
// Response is true for successful unsubscribe
});
}
registerErrorListener() {
// Invoke onError empApi method
onError((error) => {
console.error(
'Received error from server: ',
JSON.stringify(error)
);
// Error contains the server-side error
});
}