Reputation: 143
I am trying to get the returning value of a function into the svelte component. However, my functions are structure in this way:
<script>
import { Modal, Button, Card } from "svelte-chota";
let modal_open = false;
let recordsObject = {};
let records = [];
const apiURL =
"...src/Data/data.json";
// Fetch data from the API
async function getDataFromApi() {
const response = await fetch(apiURL);
recordsObject = await response.json();
records = recordsObject.records;
// Server responses is OK then
if (response.status === 200) {
console.log("Success");
} else {
// Otherwise check the error
throw new Error(response.status);
}
// Stats Functions
// Count total records
function countTotalRecords(totalRecord) {
totalRecord = console.log(records.length);
return totalRecord;
}
countTotalRecords();
}
</script>
<!-- Button to display stats -->
<Button on:click={(event) => (modal_open = true)}><pre>📊 Stats</pre></Button>
<Modal bind:open={modal_open}>
<Card>
<div>
<b><p>Below you will find the list of stats:</p></b>
**<p>Total Records: {totalRecord}</p>**
<p>Count of different event types:</p>
<p>Min delay between intereactions:</p>
<p>Max delay between intereactions:</p>
<p>Mean delay between intereactions:</p>
<p>Length of the longest sequence ("Topics filtered"):</p>
<p>Total Time of All interactions:</p>
</div>
</Card>
</Modal>
The problem is this part:
<p>Total Records: {totalRecord}</p>
Error: 'totalRecord' is not defined svelte(missing-declaration)
I want to achieve is when I click on the model "Stats", the model will show up and must display the value {totalRecord}.
Please, is anybody able to help me to figure this out? By searching on the internet. I have read that I would need to export variables or use bind, or stores... Honestly, I am a bit confused about how to achieve this. Thank you
Upvotes: 0
Views: 4501
Reputation: 22237
As mentioned in the comments, you need a variable declared to use it in a template. Then, when the value is available, you can update that variable. Initially your template will show zero, then when the data loads it will change to be the right value.
import { Modal, Button, Card } from "svelte-chota";
let modal_open = false;
let recordsObject = {};
let records = [];
// variables declared here should be available in your templates, hopefully
let totalRecord = 0;
const apiURL =
"...src/Data/data.json";
// Fetch data from the API
async function getDataFromApi() {
const response = await fetch(apiURL);
// Server responses is OK then
if (response.status === 200) {
console.log("Success");
} else {
// Otherwise check the error
throw new Error(response.status);
}
// do this after you know response.status is ok
recordsObject = await response.json();
records = recordsObject.records;
// set the above variable to the right value
totalRecord = records.length;
}
Upvotes: 2