My Stories

Overview

  • Authentication Handling: Updates the navigation buttons based on whether the user is logged in.
  • Loading Published Stories: Fetches the list of published stories from the backend API and displays them.
  • Viewing Story Content: Loads the content of a selected story when clicked.
  • Accordion Functionality: Allows for expanding and collapsing the story content in an accordion-style UI.

Key Sections

1. updateAuthButtons()

This function checks if the user is logged in by verifying the presence of a token in localStorage. It then updates the authentication buttons accordingly.

function updateAuthButtons() {
const authButtonsContainer = document.getElementById("auth-buttons");
const token = localStorage.getItem("token");

authButtonsContainer.innerHTML = ""; // Clear existing buttons

if (token) {
authButtonsContainer.innerHTML = `
<a href="myaccount" class="btn">My Profile</a>
<a href="mydrafts" class="btn">My Drafts</a>
<a href="mystories" class="btn">My Stories</a>
<a href="#" class="btn" onclick="logout()">Logout</a>
`;
} else {
authButtonsContainer.innerHTML = `
<a href="login" class="btn">Login</a>
<a href="register" class="btn">Register</a>
`;
}
}

2. logout()

When the user clicks the logout button, the logout() function clears the token from localStorage, updates the buttons, and redirects the user to the login page.

function logout() {
localStorage.removeItem("token");
alert("Logged out successfully!");
updateAuthButtons();
window.location.href = "login"; // Redirect to login
}

3. loadPublishedStories()

This function fetches the published stories from the API and displays them on the page. It first checks if the user is logged in by verifying the token, and if not, it prompts them to log in.

async function loadPublishedStories() {
const token = localStorage.getItem("token");
if (!token) {
alert("You must be logged in to view your published stories.");
return;
}

try {
const response = await fetch("/api/my-stories", {
headers: { Authorization: `Bearer ${token}` },
});

if (!response.ok) throw new Error("Failed to load published stories");

const { published } = await response.json();
const publishedList = document.getElementById("published-list");
publishedList.innerHTML = ""; // Clear existing published
const storyContent = document.getElementById("story-content");

if (published && published.length > 0) {
published.forEach((story) => {
const listItem = document.createElement("li");

const storyLink = document.createElement("a");
storyLink.href = "#";
storyLink.className = "story-link";
storyLink.dataset.id = story.id; // Store story ID
storyLink.textContent = story.title;

// Click event to load story content
storyLink.onclick = function () {
loadStoryContent(story.id);
};

listItem.appendChild(storyLink);
publishedList.appendChild(listItem);
});

// Load the first published story's content as default
loadStoryContent(published[0].id);
} else {
storyContent.innerHTML =
"<p>No published stories found. Start creating stories!</p>";
}
} catch (error) {
console.error("Error loading published stories:", error);
document.getElementById("story-content").innerHTML =
"<p>Error loading published stories. Please try again.</p>";
}
}

4. loadStoryContent()

When a user clicks on a story title, this function loads and displays the content of the selected story. It also includes the author’s information and the publication date.

async function loadStoryContent(storyId) {
const token = localStorage.getItem("token");

if (!token) {
alert("You must be logged in to view story content.");
return;
}

try {
const response = await fetch(`/api/stories/${storyId}`, {
headers: { Authorization: `Bearer ${token}` },
});

if (!response.ok) throw new Error("Failed to load story content");

const story = await response.json();
document.getElementById("story-content").innerHTML = `
<h3>${story.title}</h3>
<p class="submitted-info"><sub>Submitted By: ${
story.authorFirstName
} ${story.authorLastName} | Published on: ${new Date(
story.publishedOn
).toLocaleDateString()}</sub></p>
<p>${story.content}</p>
`;
} catch (error) {
console.error("Error loading story content:", error);
document.getElementById("story-content").innerHTML =
"<p>Error loading story content. Please try again.</p>";
}
}

5. Accordion Functionality

This code allows the user to click to expand or collapse the content of the story titles. It toggles the visibility of the story content by changing the aria-expanded attribute and showing or hiding the content.

// Accordion functionality for published stories
document.querySelectorAll(".accordion-button").forEach((button) => {
button.addEventListener("click", () => {
const content = button.nextElementSibling;
const isExpanded = button.getAttribute("aria-expanded") === "true";

// Toggle active class for content
content.classList.toggle("active");
button.setAttribute("aria-expanded", !isExpanded);

// Show or hide the clicked accordion
content.style.display = content.classList.contains("active")
? "block"
: "none";
});
});

6. window.onload

On page load, it updates the authentication buttons and loads the published stories.

window.onload = () => {
updateAuthButtons(); // Update buttons on page load
loadPublishedStories(); // Load published stories on startup
};