Obtaining JSON information with Svelte

I'm currently facing a mental block.

My goal is to fetch JSON data using the Youtube API.

The error message I am encountering is "Cannot read property 'getJSON' of undefined". Here's the code snippet I have provided:

<script>
  export let videoData = {};
  const { HEADING, HEADING2, SERVICE_LIST } = videoData;

  import  { onMount  } from "svelte";
  var key = 'my api key';
  var url = 'https://www.googleapis.com/youtube/v3/channels';
  var channelid = 'my channel id';


  var options = {
    part: 'snippet',
    key: key,
    id: channelid,
    maxresults: 20

  };
  loadvids();
  function loadvids(){
    this.getJSON(url, options, function(data){

        console.log(data);
    });
  }

</script>

This code snippet is located inside a .svelte file. Any assistance on resolving this issue would be highly valued.

Answer №1

To ensure asynchronous behavior, it is necessary to override the onmount method in your code:

const endpoint = 'https://www.googleapis.com/youtube/v3/channels';
let result = [];


onMount(async function() {
        const resp = await fetch(endpoint, config);
        result = await resp.json();
    });

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

What is the most effective way to programmatically select checkboxes based on array values in

Trying to keep it concise :) Working on a project that generates multiple pages of thumbnail images with checkboxes. The total thumbnails vary and are sorted into 1000 item html pages, called by a parent html page via iframe. Goal is for users to check che ...

Unable to forward to another page using NodeJS (Express)

After spending a considerable amount of time trying to find a solution, I finally managed to create a simple button click redirection using NodeJS and Express. However, when clicking on the "Next page" button in my index.html file, I encountered an error s ...

The failure within the internal request resulted in the failure of the main request

I develop a Jquery Promise with the following structure: request1() .then(response => {}) .then( () => { request2().done(response => {}) } .fail(err => {}); In the done and fail blocks, I implement code to "unblock" the scre ...

The replacement of classes in ReactJS using JavaScript seems to be malfunctioning

I have been attempting to change the class of a dynamic element when clicked, but none of my solutions seem to be working. Here is what I have tried: handleClick=(event,headerText)=>{ document.getElementsByClassName('sk-reset-filters') ...

Ways to confine the tabindex within a specific div container

I am currently working on identifying examples of bad accessibility practices. Specifically, I am focusing on issues related to Keyboard Focus. The first example I have encountered is the lack of visibility when trying to navigate through a set of buttons. ...

Merging two arrays together in JavaScript

Within my possession are two arrays: var g= [ { id: 36, name: 'AAA', goal: 'yes' }, { id: 40, name: 'BBB', goal: 'yes' }, { id: 39, name: 'JJJ', goal: 'yes' }, { ...

Tricks for refreshing cached web page assets in the year 2023

So far, here are some of the old Cache Buster techniques I've come across: Adding a query string in the link src: /mstylesheet.css?cache_buster=12345 Changing the filename each time: /mstylesheet-12345.css Using Apache with Cache-Control "must-revali ...

Error encountered: Unexpected character 'u' found at the start of JSON parsing. Position 0

Looking for guidance on writing jest test cases for a submit function that involves JSON.parse. The code and test case are provided below. handleFormSubmit = (e) => { e.preventDefault(); let requestData = JSON.parse ...

Ignore JSON properties that encompass all other objects in a secure manner

Currently working on a project using Spring Boot and dealing with JSON parsing using Jackson. The format of the file I am parsing is demonstrated below: { "grouping": [ { "obj1": "value1", "obj2": "value2", ...

Combine several pages from PDF files into a single document

I am currently working on developing a small electron application that combines multiple PDF files or pages into one larger page to help save paper when printing several CAD drawings. Essentially, I am looking for a cross-platform solution similar to the ...

Switch the cursor to display the magnifying glass icon for zooming in and out

I am curious about how to modify the cursor shape to display a zoom in and zoom out symbol. Changing the cursor to indicate busy or wait status is something I am familiar with, document.manual_production.style.cursor='wait'; However, I am unsu ...

Preserving the video's aspect ratio by limiting the width and height to a maximum of 100%

I am trying to integrate a YouTube video using their embed code in a "pop-up". However, I am facing an issue where the video does not resize to fit within the height of its parent. I want it to be constrained by the div#pop-up that contains the video. Curr ...

Prevent the left border from displaying on a link that wraps to a new line

Excuse me, I am facing an issue with a pipe separator in my subnav bar between links. The problem is that the first link on a new line retains the left-border that should be disabled. How can I prevent this border from appearing on the first link of a new ...

Mobile Devices Experiencing Issues with Proper Resizing of Three.JS Panorama

I'm currently working on a project using Three.Js and its device orientation library to create a panorama that users can navigate by moving their phones. Initially, everything looks great as intended: Proper Panorama However, upon refreshing the pag ...

Struggling to update state in React despite attempts to modify the state

Even though I have set the defaultAccount state to the metamask account, when trying to print it in the code below, it still shows null. The issue arises with fetching the value of defaultAccount. (Please see the error image below) class App extends Compo ...

Compare the versions of React used in the linked library and the workspace application

As I work on developing a React library containing my commonly used components, I have organized my project structure in the following way: In the root folder, there is my rollup config file and the src/ folder which houses my library. Upon building, the ...

Challenges arise when using ui-select with both multiple selection and asynchronous options

I'm encountering an issue with the ui-select directive (using AngularJS 1.6.4 and Ui-select 0.19.8). You can find my created fiddle here. The dropdown is supposed to display contacts when I type more than 3 characters, without any filtering applied ...

Turn off automatic downloading of embedded frame content in Safari for iOS

I am encountering an issue with a modal that displays a PDF and offers two options - one to print and one to download. The download option uses a blob with content-type: application/octet-stream, while the print option utilizes a blob with content-type: a ...

Surprising outcomes encountered when playing audio with JavaScript

https://i.sstatic.net/1jz45.png I've been diving into learning JavaScript and decided to create a simple web page. This page, when Pikachu (image) is clicked, plays an audio file. Similarly, if the string "Pikachu" is typed into the form, it should ...

encountering difficulties with parsing JSON data within JQuery script on Laravel 5.2

In my Laravel project, I am attempting to dynamically populate a second dropdown menu based on the value selected in the first dropdown. This process involves using AJAX to update the options available in the second dropdown when a Cinema Hall is selected. ...