Skip to content

πŸ’½ UserData (API)

Bart edited this page Jun 19, 2024 · 2 revisions

File: Meesterproef-SNSimulation/js/UserData.js

Description

The UserData class handles fetching and managing user data and post data. It pre-fetches data from APIs and provides methods to retrieve user and post data as needed. The class retrieves both fake and real data from APIs.

Methods

  • constructor(): Initializes a new instance of the UserData class, pre-fetching user and post data.

  • fetchUserData(count): Fetches random user data from an API.

    • Parameters:
      • count (number): The number of users to fetch.
    • Returns: Promise - Resolves when the data has been fetched and processed.
    • View Code
  • get(count): Retrieves a specified number of pre-fetched users. If insufficient data is available, it fetches more.

    • Parameters:
      • count (number): The number of users to retrieve.
    • Returns: Array - An array of user data objects.
    • View Code
  • getPosts(count): Retrieves a specified number of random posts from the pre-fetched post data.

    • Parameters:
      • count (number): The number of posts to retrieve.
    • Returns: Array - An array of post data objects.
    • View Code
  • fetchRealPostData(): Fetches real post data from an RSS feed, converting the XML data to JSON format.

    • Returns: Promise - Resolves when the data has been fetched and processed.
    • View Code

Fetch User Data from API

This guide explains how to use an asynchronous function to fetch user data from the randomuser.me API and process the fetched data. The function retrieves a specified number of user profiles, extracts the necessary details, and stores them in an array.

Code Explanation

Here is the complete code snippet with detailed comments:

async fetchUserData(count) {
    // Fetch user data from the randomuser.me API
    const response = await fetch(`https://randomuser.me/api/?results=${count}`);
    
    // Parse the JSON response
    const data = await response.json();

    // Iterate over each person in the results array
    data.results.forEach((person) => {
        // Create an object with the person's image URL and full name
        let personData = {
            image: person.picture.large, // User's large picture URL
            username: person.name.first + " " + person.name.last, // User's full name
        };
        
        // Add the person's data to the preFetchedData array
        this.preFetchedData.push(personData);
    });
}

Detailed Function Breakdown

Function Definition

  • async fetchUserData(count): An asynchronous function named fetchUserData that takes a single parameter count. The async keyword allows the function to use await inside it.

Fetching Data

  • const response = await fetch(...): Uses the fetch API to make an HTTP GET request to https://randomuser.me/api/?results=${count}. The await keyword pauses the function execution until the promise returned by fetch resolves. The number of results is determined by the count parameter.

Parsing Response

  • const data = await response.json();: The response from fetch is a Response object. The json method is called on this object to parse the response body as JSON. await pauses execution until the promise resolves with the parsed JSON data.

Processing Data

  • data.results.forEach((person) => { ... });: The data object contains a results array with user data. The forEach method iterates over each person in this array.

Extracting and Storing User Data

Inside the forEach loop, a personData object is created with two properties:

  • image: The URL to the user's large picture.
  • username: The user's first and last name concatenated with a space.

This personData object is then pushed to the preFetchedData array of the class or object.

Design rational

Clone this wiki locally