Problem: I need help fixing an issue with my js file and updating my code, so the program will not reset every time I return to the initial page.
Program: The functionality of the site works as follows: Running the program on the localhost will first prompt the user to input a username. This username is used as ID for the user chat/channel. Additionally, the user is able to create and join multilipe channels. If two hosts are running concurrently and have joined the same chat, then the users can send messages to each other and update instantly.
Here's the Repository: https://github.com/NilesDobbs/Assignment14
Goal: Right now, the functionality I'm aiming for is that once a user inputs their username and starts a chat in the room, if they were to return to /welcome manually, the program would save their name, and the page would not ask them to input their name again and send them directly to the site. The only clue I've been given is that it has to do with a check involving my welcome.js file:
let username = prompt('Enter your name')
fetch("/welcome/createuser", {
method : "POST",
headers: {
"Content-Type" : "application/json"
},
body: username
})
.then((response) => response.json())
.then(user =>
sessionStorage.setItem("user",JSON.stringify(user)))
Any help would be appreciated at this moment. Thank you.
You can check if the username is already in session before prompting the user to input a username
if(sessionStorage.getItem("user")){
// set chat user to sessionStorage.getItem("user")
let username = sessionStorage.getItem("user")
} else {
let username = prompt("Enter your name");
fetch("/welcome/createuser", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: username,
})
.then((response) => response.json())
.then((user) => sessionStorage.setItem("user", JSON.stringify(user)));
}