Skip to main content

JavaScript Example

This example demonstrates how to call the Mockd API using the fetch API and use the returned results to call another function. This is helpful if you need to update a UI or submit the response to a database.

JavaScript Example
// A function that processes the data received from Mockd
function processUserData(userData) {
console.log("Processing user data...");
console.log(`User Name: ${userData.name}`);
console.log(`User Email: ${userData.email}`);

// You can perform more actions here, like updating the UI or saving to a database
}

// Calling the Mockd API
fetch("https://api.mockd.info/", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
fields: {
name: "male-full-name",
email: "email",
},
}),
})
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then((data) => {
console.log("Mockd API Response:", data);

// Using the results of the Mockd API call to call another function
processUserData(data);
})
.catch((error) => {
console.error("Error fetching data from Mockd:", error);
});

Explanation

  1. processUserData(userData): This is the "another function" that is called with the results from the Mockd API. In a real-world scenario, this could be any function in your application that needs the mock data.
  2. fetch("https://api.mockd.info/", ...): We use the standard fetch API to make a POST request to Mockd.
  3. headers: We set the Content-Type to application/json as required by the Mockd API.
  4. body: We define the fields we want Mockd to generate. In this case, a male-full-name and an email.
  5. .then(response => ...): We check if the request was successful and convert the response to JSON.
  6. .then(data => ...): This is where the magic happens. We receive the generated data and pass it directly to our processUserData function.