Build an fCC Forum Leaderboard - Build an fCC Forum Leaderboard

Tell us what’s happening:

i don’t know, it seems to work. it fails test 28 and 29

Your code so far

const forumLatest =
  'https://cdn.freecodecamp.org/curriculum/forum-latest/latest.json';
const forumTopicUrl = 'https://forum.freecodecamp.org/t/';
const forumCategoryUrl = 'https://forum.freecodecamp.org/c/';
const avatarUrl = 'https://sea1.discourse-cdn.com/freecodecamp';

const allCategories = {
  299: { category: 'Career Advice', className: 'career' },
  409: { category: 'Project Feedback', className: 'feedback' },
  417: { category: 'freeCodeCamp Support', className: 'support' },
  421: { category: 'JavaScript', className: 'javascript' },
  423: { category: 'HTML - CSS', className: 'html-css' },
  424: { category: 'Python', className: 'python' },
  432: { category: 'You Can Do This!', className: 'motivation' },
  560: { category: 'Backend Development', className: 'backend' }
};

const timeAgo = (timestamp) => {
  const currTime =  Date.now()
  const timestampTime = new Date(timestamp).getTime();
  const timeDiffMs = currTime - timestampTime; 
  const minutes = Math.floor(timeDiffMs / 60000);
  const hour = Math.floor(minutes / 60);
  const days = Math.floor(hour / 24);

  if (minutes < 60) {
    return `${minutes}m ago`
  } else if (hour < 24) {
    return `${hour}h ago`
  } else {
    return `${days}d ago`
  } 
};

const viewCount = (views) => {
  if (views >= 1000) {
    return `${Math.floor(views / 1000)}k`
  } else {
    return views
  }
};

const forumCategory = (id) => {
  if (allCategories.hasOwnProperty(id)) {
  const categoryId = allCategories[id];
  const category = categoryId.category;
  const className = categoryId.className;
    return `<a class="category ${className}" href="${forumCategoryUrl}${className}/${id}">${category}</a>`
  } else {
    return `<a class="category general" href="${forumCategoryUrl}general/${id}">General</a>`
  }
};

const avatars = (posters, users) => {
  let imagesHTML = "";
  posters.forEach((poster) => {
    const id = poster.user_id;
    const user = users.find(user => user.id === id);
    if (user && typeof user.avatar_template === "string") {
      const url = user.avatar_template.replace("{size}", "30");
      const fullUrl = url.startsWith("/") ? `${avatarUrl}${url}` : url;
      imagesHTML += `<img alt="${user.name}" src="${fullUrl}"/>`;
    } else {
      console.warn(`Nessun avatar per user_id ${id}`);
    }
  });
  
  return imagesHTML
}

const generateTable = (obj) => {
  const users = obj.users;
  const topicList = obj.topic_list.topics;
  let tableHTML = "";
  if(Array.isArray(topicList)) {
    topicList.forEach((topic) => {
      const id = topic.id;
      const title = topic.title;
      const views = topic.views;
      const postsCount = topic.posts_count;
      const slug = topic.slug;
      const posters = topic.posters;
      const categoryId = topic.category_id;
      const bumpedAt = topic.bumped_at;
      tableHTML += 
      `<tr>
          <td>
            <a class="post-title" href="${forumTopicUrl}${slug}/${id}">${title}</a>
            ${forumCategory(categoryId)}
          </td>
          <td>
            <div class="avatar-container">${avatars(posters, users)}</div>
          </td>
          <td>${postsCount - 1}</td>
          <td>${views}</td>
          <td>${timeAgo(bumpedAt)}</td>
        </tr>`
    })
  }
  return tableHTML
}

const showLatestPosts = (obj) => {
  const postsContainer = document.getElementById("posts-container");
  postsContainer.innerHTML = generateTable(obj);
}  

const fetchData = () => {
  fetch("https://cdn.freecodecamp.org/curriculum/forum-latest/latest.json")
  .then((response) => response.json())
  .then((data) => {
    setTimeout(() => {
  showLatestPosts(data);
}, 100)})
  .catch((err) => {
    console.log(err)
  })
}

document.addEventListener("DOMContentLoaded", fetchData);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36

Challenge Information:

Build an fCC Forum Leaderboard - Build an fCC Forum Leaderboard
https://www.freecodecamp.org/learn/full-stack-developer/lab-fcc-forum-leaderboard/build-an-fcc-forum-leaderboard

What are tests 28 and 29? Which lines of code are related to these tests? What debugging have you tried?

Here are some basic troubleshooting steps you can follow. Focus on one test at a time:

  • What is the requirement of the first failing test?
  • Double check the related User Story and ensure it’s followed precisely.
  • What line of code is involved?
  • What is the result of the code and does it match the requirement? You can write the value of a variable to the console at that point in the code to check if needed.
  • Is there any other output or messages in the console to follow up on?

If this does not help you solve the problem, please reply with answers to these questions.

the tests i fail are
28. Your fetchData function should call showLatestPosts
29. If there is an error, your fetchData function should log the error to the console, using console.log.
But if you try my code it works.
usually i search the error in the console to see what’s wrong with my code but this time i find 2 error that i can’t understand, this:

dom-test-evaluator.js:2 Error: AssertionError: expected [] not to be empty
    at eval (eval at #a (dom-test-evaluator.js:2:254989), <anonymous>:13:11)
    at async #a (dom-test-evaluator.js:2:255329)
    at async DOMTestEvaluator.handleMessage (dom-test-evaluator.js:2:256038)
#a @ dom-test-evaluator.js:2
await in #a
handleMessage @ dom-test-evaluator.js:2
onmessage @ dom-test-evaluator.js:2
dom-test-evaluator.js:2 Error: This is a test error
    at fetch (eval at #a (dom-test-evaluator.js:2:254989), <anonymous>:11:13)
    at fetchData (about:srcdoc:357:3)
    at eval (eval at #a (dom-test-evaluator.js:2:254989), <anonymous>:13:11)
    at #a (dom-test-evaluator.js:2:255335)
    at async DOMTestEvaluator.handleMessage (dom-test-evaluator.js:2:256038)
#a @ dom-test-evaluator.js:2
await in #a
handleMessage @ dom-test-evaluator.js:2
onmessage @ dom-test-evaluator.js:2
build-an-fcc-forum-leaderboard:1 The resource https://www.freecodecamp.org/static/Hack-ZeroSlash-Italic-678bc16b550480d5a3c5c76dbf8c5fb9.woff was preloaded using link preload but not used within a few seconds from the window's load event. Please make sure it has an appropriate `as` value and it is preloaded intentionally.
build-an-fcc-forum-leaderboard:1 The resource https://www.freecodecamp.org/static/Hack-ZeroSlash-Bold-c8ea19a8461596cf1a6a2ad08bebcf8e.woff was preloaded using link preload but not used within a few seconds from the window's load event. Please make sure it has an appropriate `as` value and it is preloaded intentionally.
build-an-fcc-forum-leaderboard:1 The resource https://www.freecodecamp.org/static/Lato-Light-91308c0216b40aad16036f1394b98237.woff was preloaded using link preload but not used within a few seconds from the window's load event. Please make sure it has an appropriate `as` value and it is preloaded intentionally.
build-an-fcc-forum-leaderboard:1 The resource https://www.freecodecamp.org/static/Hack-ZeroSlash-Regular-f67447de5dc6604f538786bd55ac6019.woff was preloaded using link preload but not used within a few seconds from the window's load event. Please make sure it has an appropriate `as` value and it is preloaded intentionally.

Focus on one test at a time:

  1. Your fetchData function should call showLatestPosts

Double check the related User Story and ensure it’s followed precisely.
What line of code is involved?

I notice that you are using setTimeout to call showLatestPosts. Why is that? It’s not mentioned in the instructions.

The fetchData function should request data from forumLatest and call showLatestPosts passing it the response parsed as JSON.

i write it i n the other reply

i try the setTimeout to see if that was the problem, the test fails even if i delete the timeout and even if i remove the function generateTable and move all the related code back in the showLatestPost function

Double check the related User Story and ensure it’s followed precisely.

Check User Story 17 as it’s related to fetchData

i’m sorry i don’t understand

Did you read User Story 17 and see how it’s related?

Are you familiar with an asynchronous function?

(What don’t you understand?)

i dont understand what is user story 17, i’m not a master in asynchronous function but you see the fetch i made in my code, what is wrong? the code works, the forum is showed, just the img are not working but neither in the example project, i write in another reply even the error that log in the console and, for what i understand, itìs not my fault. can you please help me and don’t treat me like i’m dumb?

I’m not trying to be condescending, I’m really trying to find out what you know or don’t know. If you just say “I don’t understand” it’s really hard for me to know exactly what to explain.

Even if your code “works” it needs to follow the user stories to pass the tests. The tests will be expecting specific things.

User Story 17 is part of the instructions.

  1. You should have an async function named fetchData.

An async function is a specific thing, you can do a search for it for more information to remind yourself.

https://www.w3schools.com/Js/js_async.asp

maybe i understand, i thougth that fetch was an asyncrounous function but the test wants strictly a function with async and await?

Exactly, they are different ways to do the same thing, but the story is specifically asking that fetchData is designated as an “async function” and not just a regular function

Thank you so much and sorry for the reply. I’m sorry, but sometimes tests are a bit complicated to understand exactly. It’s really annoying when the code works and the tests fail.

No problem, I can totally understand how “What don’t you understand” comes off as rude, but sometimes we just need more information about what to explain.

100% the stories and tests can be complicated, been there. Just keep in mind to really review the user stories as they need to be followed very specifically and you can’t add anything extra.

You can imagine how hard it is to create automated tests for programming tasks which could be completed in any number of ways.

The setTimeout for example could result in working code but maybe the test will run before the setTimeout executes so it won’t be seen by the test.

I can imagine how hard it is and I will never stop thanking you for this opportunity, I promise myself that as soon as I am better financially I will become a sub for life.