Trying to access the localStorage when the page completely loads. Since it was showing null, I used settimeout
to fetch the data after 500sec, later I tried to load the page and got the below error.
Error while loading
Cannot set properties of null (setting 'innerHTML')
TypeError: Cannot set properties of null (setting 'innerHTML')
at http://localhost:9000/root-config.js:241:26
if I refresh the page it works fine
LoginMfe.js
navigate("/home");
const customEvent = new CustomEvent('sharedAvatarText');
window.dispatchEvent(customEvent);
Root-config.js
import { registerApplication, start, navigateToUrl } from "single-spa";
import * as singleSpa from 'single-spa';
import {
constructApplications,
constructRoutes,
constructLayoutEngine,
} from "single-spa-layout";
import microfrontendLayout from "./microfrontend-layout.html";
const routes = constructRoutes(microfrontendLayout);
const applications = constructApplications({
routes,
loadApp({ name }) {
return System.import(name);
},
});
const layoutEngine = constructLayoutEngine({ routes, applications });
applications.forEach(registerApplication);
window.addEventListener('sharedAvatarText',getAvatarText );
function getAvatarText() {
const givenName = (
JSON.parse(JSON.parse(localStorage.getItem("user")).result).given_name[0] +
JSON.parse(JSON.parse(localStorage.getItem("user")).result).family_name[0]).toUpperCase();
setTimeout( () => {
const avatarText = document.getElementById("avatar_text");
console.log("text",avatarText)//null for the first load;
avatarText.innerHTML = givenName;
},200)
}
layoutEngine.activate();
start();
const button = document.getElementById("logout_Button") ;
if (button) {
button.addEventListener("click", function() {
localStorage.clear();
navigateToUrl("/login");
});
}
window.onload = function() {
const storedUser = JSON.parse(localStorage.getItem("user"));
if (storedUser && storedUser.result) {
const givenName = (
( JSON.parse(storedUser.result).given_name && JSON.parse(storedUser.result).given_name[0] || '') +
( JSON.parse(storedUser.result).family_name && JSON.parse(storedUser.result).family_name[0] || '')
).toUpperCase();
const avatarText = document.getElementById("avatar_text");
avatarText.innerHTML = givenName;
}
}
I am expecting that when the login is successful the event is triggered and should fetch the data from local storage.