Obtaining a random generated number through an API request, and utilizing this number as an input parameter for a subsequent API call

I'm currently working on a unique "Show - Actor - Show" button that will display a random show, followed by a cast member from that show, and then another show featuring the same cast member.

While I've managed to generate a random show ID successfully, I am facing challenges in passing that ID into the randomActor function because randomShow isn't a function.

My goal is to have a single button that switches between searching for an actor or show based on the previous search. The main issue lies with my randomActor function as I am struggling to pass the value of the randomShow search into the string template literal.

Any help or advice would be greatly appreciated!

const randomButton = document.querySelector('#randomShow')
const randomShow = randomButton.addEventListener('click', async function (e) {
    e.preventDefault();
    const randomNumber = Math.floor(Math.random() * 1000);
    const res = await axios.get(`http://api.tvmaze.com/shows/${randomNumber}`)
    console.log(res.data.id);
    return (res.data.id)
})

const randomActor = randomActorButton.addEventListener('click', async function (e) {
    e.preventDefault();
    const res = await axios.get(`http://api.tvmaze.com/shows/${randomShow.res.data.id}/cast`)
    console.log(res.data[0]);
    return (res.data[0])
})

Answer №1

Don't expect the eventListener to return the function result within its listener

This example demonstrates how to work around this:

const randomButton = document.querySelector('#randomShow');
let randomShow = "";
randomButton.addEventListener('click', async function(e) {
  e.preventDefault();
  document.getElementById("actor").innerHTML = "";
  const randomNumber = Math.floor(Math.random() * 1000);
  const res = await axios.get(`https://api.tvmaze.com/shows/${randomNumber}`)
  document.getElementById("show").innerHTML = res.data.name;
  randomShow = res;
})


const randomActorButton = document.querySelector('#randomActor')
randomActorButton.addEventListener('click', async function(e) {
  e.preventDefault();
  if (randomShow) {
    const res = await axios.get(`https://api.tvmaze.com/shows/${randomShow.data.id}/cast`)
    console.log(res.data)
    document.getElementById("actor").innerHTML = res.data[Math.floor(Math.random(res.data.length))].person.name;
  }
  else console.log("No show")
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.0/axios.min.js" ></script>

<button type="button" id="randomShow">Random show</button>
<button type="button" id="randomActor">Random Actor</button>

<span id="show"></span> <span id="actor"></span>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The inclusion of jquery.ui results in a 400 bad request error

I currently have my HTML structured like this <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %> <script src="http://code.jquery.com/jquery-1.10.2.js"></script> <script src="http://code.jquery.com/ui/1.1 ...

Jquery modal dialog experiencing issues with controls not working properly

In my ASP.net web app, I am utilizing the jQuery dialog. Inside this dialog, there is a user control with some links. However, when the dialog is set to modal mode, the links become unselectable. I attempted the solution mentioned in this post, but unfort ...

AngularJS full height style with Google Maps integration

I'm having trouble displaying a full-height Google map on my website. <section data-ng-controller="LocationsController" data-ng-init="find()"> <map center="41.454161, 13.18461" zoom="6"> <span data-ng-repeat="location in locations" ...

What are some ways to improve this?

This specific code snippet is a crucial component of a weather widget designed for iPhone devices. While the current implementation is functional, I am seeking advice on how to optimize it in order to avoid duplicating the fail function. Any insights or ...

Switch up the format of a JSON data structure using JavaScript

I am facing an issue with converting a JSON structure into another format. I would appreciate any help or suggestions on this matter. I have tried different methods and alternatives for conversion, but I am still searching for the most efficient way to a ...

I am unable to pass the req.params.id value as an input to a function located in a separate file

In my project, I've developed a REST API for user and coupon management. The main file driving this API is called coupon-api.js. This file contains the route definitions, while the functions to handle these routes are separated into two distinct files ...

NodeJS:UncaughtPromiseError

Each time the command npm run start is executed, everything appears to be normal and the logs indicate no issues until encountering the following error: (node:4476) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'length' of und ...

Creating a dynamic traffic light display: A step-by-step guide

//traffic lights:red,yellow,green fill(trafficFirstLightColor) ellipse(315, 40, 20, 20) fill(trafficSecondLightColor) ellipse(315, 40 + 25 * 1, 20, 20) fill(trafficThirdLightColor) ellipse(315, 40 + 25 * 2, 20, 20) //if three ...

Angular.js has a unique filter that allows users to customize the date format to their preference

My upcoming event is happening on "endDate": "2014-11-30 01:00:00.0", in JSON format. I want to display it as 30 Nov 2014. I attempted to display it using: {{ phone.endDate | date:'medium' }} within an HTML document. Unfortunately, it is sti ...

How can we implement a select-all and deselect-all feature in Vue Element UI for a multi-select with filtering capability?

As a newcomer to VueJs, I am exploring how to create a component that enables multiple selection with a search option and the ability to select all or deselect all options. To achieve this functionality, I am utilizing the vue-element-ui library. You can ...

Error: Unable to access the 'category_affiliation' property of null

After implementing a login function using redux state, I encountered an issue upon logging in. The error message TypeError: Cannot read properties of null (reading 'category_affiliation') is being displayed in my Sidebar.jsx file. It seems like t ...

Display dynamic form with database value on click event

Seeking assistance to create a JavaScript function or any other method to address the issue I am facing. Currently, I have a functional pop-up form and a table connected to a database with queries. The pop-up form successfully appears upon clicking, howeve ...

Retrieve encoded cookies using PHP and JavaScript

My JS code sets cookies named after the courses we offer. To handle special characters and whitespaces, I encoded them using encodeURIComponent() as shown below: $("button[id='ajouter_panier_"+value+"']").click(function(){ $( "div[id=&ap ...

Do not fulfill the promise until all the images have finished loading

Below is the intended process: Iterate through a collection of img tags Retrieve each tag's src URL Convert it to a base64 encoded string using an HTML 5 canvas Once all images have been converted, resolve the promise and call the callback function ...

Could you provide the parameters for the next() function in Express?

Working with Express.js to build an API has been a game-changer for me. I've learned how to utilize middlewares, handle requests and responses, navigate through different middleware functions... But there's one thing that keeps boggling my mind, ...

What is the specific character code assigned to the "Enter" key on a

Check out this code snippet: http://jsfiddle.net/YttKb/ In my javascript, I am trying to add a new line of text using utf-8 coding. Which character should I use to make a new line? It seems like \n only creates a line break, not a new line of text. ...

A guide on showcasing specific data within ng-repeat by referencing another property in JSON object

After retrieving a JSON file using $http(), the structure looks something like this: [ { "sno": "3", "eventname": "hockey", "event-type": "sports", "A-team": "mme", "B-team": "eee", "Gender": "male", "time": "2017-11-24 00:00:00", "isres ...

Creating a cube with unique textures on each face in three.js r81: What's the best way to achieve this?

After updating to the latest version of three.js, I encountered an issue where THREE.ImageUtils.loadTexture no longer works. As a result, I tried searching for examples of cubes with different faces, but they all utilized the outdated technique "new THREE. ...

Encountering an issue while attempting to send a POST response through Node Express, specifically an error related

Encountering an error after completing registration, specifically when attempting to respond to the POST request. (user is added to database successfully) express deprecated res.send(status, body): Use res.status(status).send(body) instead auth\regi ...

Tips for effectively separating HTML and JavaScript for a cleaner code structure

Is it necessary and worth it to decouple HTML and JavaScript? In JavaScript logic, you always have to use some HTML elements... I know that in C#, you can decouple for easier maintenance and testing scenarios. ...