keep user data in localstorage

This commit is contained in:
Raven Scott 2024-06-03 23:22:13 -04:00
parent 1d19fc5a9d
commit 59c1a2f776

26
app.js
View File

@ -18,6 +18,9 @@ let userAvatar = '';
let registeredUsers = JSON.parse(localStorage.getItem('registeredUsers')) || {}; let registeredUsers = JSON.parse(localStorage.getItem('registeredUsers')) || {};
let peerCount = 0; let peerCount = 0;
// Load user information from localStorage
let currentUser = JSON.parse(localStorage.getItem('currentUser')) || { username: 'Anonymous', avatar: '' };
async function initialize() { async function initialize() {
swarm = new Hyperswarm(); swarm = new Hyperswarm();
@ -50,18 +53,15 @@ async function initialize() {
messageForm.addEventListener('submit', sendMessage); messageForm.addEventListener('submit', sendMessage);
} }
const savedUser = localStorage.getItem('currentUser'); // Set current user if available in localStorage
if (savedUser) { if (currentUser.username) {
const user = JSON.parse(savedUser); userName = currentUser.username;
userName = user.username; userAvatar = currentUser.avatar || '';
userAvatar = user.avatar || '';
const setupDiv = document.querySelector('#setup'); const setupDiv = document.querySelector('#setup');
if (setupDiv) {
setupDiv.classList.remove('hidden');
}
} else {
const registerDiv = document.querySelector('#register'); const registerDiv = document.querySelector('#register');
if (registerDiv) { if (userName !== 'Anonymous' && setupDiv) {
setupDiv.classList.remove('hidden');
} else if (registerDiv) {
registerDiv.classList.remove('hidden'); registerDiv.classList.remove('hidden');
} }
} }
@ -272,3 +272,9 @@ async function updateIcon(username, avatarBuffer) {
} }
initialize(); initialize();
// Save the current user's information before closing the application
window.addEventListener('beforeunload', () => {
localStorage.setItem('currentUser', JSON.stringify({ username: userName, avatar: userAvatar }));
});