0

I am fetching json using the Svelte onMount. I have an issue with getting the return json outside the onMount statement.

This is how i fetch my JSON using onMount:

let testData = [];
    onMount(async () =>{
        const resp = await fetch('http://localhost:3000/api/tableinfo.json');
        testData = await resp.json();    
        console.log(testData);    //Returns me array of objects
    });

Console.log(testData) // return me []

How do I pass the array of objects and store in testData so that I can call testData with the array in another file?

Thank you.

Denise
  • 139
  • 1
  • 2
  • 12

1 Answers1

2

In your code, the line console.log(testData) will be executed at component instantiation, which is before the onMount runs, the expected value is []. Once the component is mounted and onMount ran, testData will have the correct value. You can try this easily be adding the following line:

$: console.log(testData)

This statement will run everytime testData will change, you will see two lines in your console, the first one with the initial value of an empty array, the second with your json fetch result.

[]
[...]
Stephane Vanraes
  • 14,343
  • 2
  • 23
  • 41
  • Okay, I managed to see the json fetch result. Thank you!! But I would like it to be stored in testData so that when I export testData to another svelte file. – Denise Oct 28 '20 at 07:38
  • since this looks like a component, you would declare it as being exported: `export let testData = []` but if this is not a component on it's own you don't need all the svelte stuff, you can simply make a `.js` file instead – Stephane Vanraes Oct 28 '20 at 08:00
  • I tried that and it wasnt showing. Now it is displaying the data. Thanks Stephane! – Denise Oct 28 '20 at 08:12