Problem:
I am trying to remove a div and alter a counter from on single button click:
<button @onclick="() => RemoveDocument(className)" class="close-button inner-div">X</button>
private async void RemoveDocument(string className)
{
AmountOfDocs--;
await JSRuntime.InvokeVoidAsync("removeDiv", className);
}
function removeDiv(elName) {
var element = document.getElementById(elName);
element.remove();
}
But if i do this, it works. The div in question is removed from the dom, but also with it comes an error message:
blazor.server.js:1 [2023-10-17T14:58:52.607Z] Error: There was an error applying batch 11.
blazor.server.js:1 Uncaught (in promise) TypeError: Cannot read properties of null (reading 'removeChild')
at H (blazor.server.js:1:17228)
at ie.applyEdits (blazor.server.js:1:21401)
at ie.updateComponent (blazor.server.js:1:20631)
at blazor.server.js:1:115262
at Pn.processBatch (blazor.server.js:1:115634)
at kt.<anonymous> (blazor.server.js:1:129816)
at blazor.server.js:1:72077
at Array.forEach (<anonymous>)
at kt._invokeClientMethod (blazor.server.js:1:72063)
at kt._processIncomingData (blazor.server.js:1:70105)
[2023-10-17T14:58:52.655Z] Error: System.AggregateException: One or more errors occurred. (TypeError: Cannot read properties of null (reading 'removeChild'))
---> System.InvalidOperationException: TypeError: Cannot read properties of null (reading 'removeChild')
at Microsoft.AspNetCore.Components.RenderTree.Renderer.InvokeRenderCompletedCallsAfterUpdateDisplayTask(Task updateDisplayTask, Int32[] updatedComponents)
--- End of inner exception stack trace ---
log @ blazor.server.js:1
tr @ blazor.server.js:1
(anonymous) @ blazor.server.js:1
(anonymous) @ blazor.server.js:1
_invokeClientMethod @ blazor.server.js:1
_processIncomingData @ blazor.server.js:1
connection.onreceive @ blazor.server.js:1
o.onmessage @ blazor.server.js:1
blazor.server.js:1 [2023-10-17T14:58:52.656Z] Information: Connection disconnected.
After that, i cannot click on any of the other buttons.
Where is my mistak?
Solution:
“Only mutate the DOM with JavaScript (JS) when the object doesn’t interact with Blazor. Blazor maintains representations of the DOM and interacts directly with DOM objects. If an element rendered by Blazor is modified externally using JS directly or via JS Interop, the DOM may no longer match Blazor’s internal representation, which can result in undefined behavior. Undefined behavior may merely interfere with the presentation of elements or their functions but may also introduce security risks to the app or server.” https://learn.microsoft.com/en-us/aspnet/core/blazor/javascript-interoperability/?view=aspnetcore-7.0