Fetching JSON data
Data from an external API can be fetched using the browser’s fetch() API. Making the @zOnStart method async allows you to use await to handle the response cleanly:
@zOnStart()private async _fetchData() { const response = await fetch('https://api.example.com/data'); const data = await response.json(); this.zcomponent.nodes.myTextNode.text = data.someField;}This method leverages the browser’s
fetchWeb API; which you can learn more about here.
Example usage
import { Behavior, zBehavior, zOnStart } from '@zcomponent/core';import Scene from './Scene.zcomp';
@zBehavior({ icon: 'cloud_download' })export class FetchDataBehavior extends Behavior<Scene> { protected zcomponent = this.getZComponentInstance(Scene);
@zOnStart() private async _fetchData() { const response = await fetch('https://api.example.com/data'); const data = await response.json();
// Update a text node with the fetched value this.zcomponent.nodes.myTextNode.text = data.someField; }}For loading that should block the experience start (e.g. required assets), consider using the
@zLoaddecorator instead, which integrates with Mattercraft’s progress screen. See Custom Components for details.