Guide 3.4: Real Projects

Fetch JAMB Questions

When the user clicks the "Start Exam" button, we need to read their selected subject, fire off an API request to SdashAPI to fetch 40 questions, and switch the UI from the home screen to the exam screen.

Global State Variables

3.4.1

Before we fetch questions, we need variables to hold the state of our examination session. Add these to the top of your app.js file.

// Exam State
let examQuestions = []; // Will hold the array of 40 questions
let currentQuestionIndex = 0; // Tracks which question the user is currently viewing
let userAnswers = {}; // Will store the user's selected options (e.g., { 0: 'a', 1: 'c' })

The Start Event

3.4.2

Now, attach an event listener to the startBtn. This function will read the dropdown value, change the button text to show a loading state, and make the fetch request.

startBtn.addEventListener('click', async () => {
  const selectedSlug = subjectSelect.value;
  if (!selectedSlug) return;

  // Show loading state
  startBtn.textContent = 'Loading Questions...';
  startBtn.disabled = true;
  subjectSelect.disabled = true;

  try {
    // We request 40 questions from the 'utme' (JAMB) category
    const url = `${API_BASE}/q?subject=${selectedSlug}&type=utme&limit=40`;
    
    const response = await fetch(url, {
      headers: { 'AccessToken': API_KEY }
    });
    
    if (!response.ok) throw new Error('Failed to fetch questions');
    
    const data = await response.json();
    examQuestions = data.data; // Save the 40 questions to our global state
    
    // Transition to the exam screen
    startExam();
    
  } catch (error) {
    console.error(error);
    alert('Error loading exam. Please try again.');
    
    // Reset UI on failure
    startBtn.textContent = 'Start Exam';
    startBtn.disabled = false;
    subjectSelect.disabled = false;
  }
});

The startExam() Function

3.4.3

Finally, we need a function that hides the home screen, shows the exam screen, and initializes the first question.

function startExam() {
  // Hide home screen
  document.getElementById('homeScreen').classList.remove('active');
  
  // Show exam screen (we will build this HTML next!)
  document.getElementById('examScreen').classList.add('active');
  
  // Render the very first question
  renderQuestion(currentQuestionIndex);
}

Where do the questions go?

Next, we need to build the HTML interface that will actually display these fetched questions.

Next Guide: Build Question Interface →
Avatar

How can we help?

We reply immediately

Hello! 👋 How can we help you today?