Fetching Data

KS
Last updated 12 days ago

Features aren't very useful if they're static. Datasources are third-party (including your server) URLs that can supply dynamic data to your feature at runtime.

Adding Datasources

You may add as many Datasources are you like to your feature, using the Datasources panel in the left tool sidebar of the Mason Builder's Configure section. Each Datasource must have a URL that responds to a GET request with an application/json payload in the response body. Data will be fetched from your Datasource when your component is first mounted.

Dynamic Parameters

You may inject dynamic header or query parameters, like authorization tokens, at runtime by using the willFetchData callback prop. These values will be merged with the values you set in the Mason Builder, with the values you provide taking precedence in the event of a conflict.

import React from 'react';
import { Feed } from 'mason-library';
class MyFeed extends React.Component {
render() {
const { search, token, user } = this.props;
return <Feed
id="YOUR_COMPONENT_ID"
willFetchData={(datasource, featureId) => {
if (datasource.name === 'Search') {
return {
headers: { 'Authorization': token },
queries: { 'search': search },
};
}
return datasource;
}} />;
/>;
}
}

Your function will receive two arguments:

datasource, an object of the following structure

{
url: 'https://example.test',
headers: {
'Content-Type': 'application/json'
},
queries: {
foo: 'bar'
},
name: 'Datasource name',

and featureId, the 12-byte unique identifier of your feature (which you can find in the Export modal in the Builder).

You must return an object, if you have no modifications return an empty object or the first argument unmodified.

Dynamic Parameters with HTML

Because events are immutable, you cannot provide dynamic parameters if you're embedding your feature as HTML. You may add an event subscriber to be notified when your feature will fetch data, however.

<mason-feed id="feed" data-id="YOUR_COMPONENT_ID"></mason-feed>
<script type="text/javascript">
const feedNode = document.getElementById('feed');
feedNode.addEventListener('mason.willFetchData', function(event) {
//show a loading notification
});
</script>

Providing Data at Runtime

In some cases you may want to use a form submission response to update a Datasource and trigger a UI update. To accomplish this, use the Success event menu in the Form tab of the Configure section of the Builder. You may merge or replace a Datasource with the response from your form submission.

Replace simply overwrites the entire datasource. When merging, the behavior is as follows:

  • if the Datasource is an object, the response will be shallowly merged

  • if the Datasource is an array, and the response is not an array, the response will be pushed onto the end of the array

  • if the Datasource is an array, and the response is an array, the response's entries will be pushed onto the end of the array