Highcharts show loading icon when fetching data in javascript - javascript

We want to show loading icon when the data loads and chart is made in highcharts.
Below is pseudo code:
// service call
// data is pushed in data set
// and that data is used in highcharts.
$('Chart_name').highcharts({
});

Render chart without data, then show loading screen, fetch data, hide loading screen.
Example:
// Options without data
const options = {
series: [{
data: [],
type: 'column'
}]
}
// Redner chart
const chart = Highcharts.chart('container', options)
// Simulate fetch request timeout, get data after some delay
setTimeout(() => {
const data = [1,2,3]
chart.hideLoading()
chart.series[0].setData(data)
}, 2000)
// Show loading screen
chart.showLoading()
Live example:
https://jsfiddle.net/hLj1advd/

Related

Apollo Client: keeping data from previous query while waiting for next fetching

I have a React-Native component that shows a map with markers (point of interests). I'm using Apollo Client to query those markers from a graphql server. Only markers within the visible map area are returned:
const { loading, data, error, refetch, networkStatus } = useQuery<
RectangleQuery,
RectangleQueryVariables
>(RECTANGLE, {
variables: { input: rectInput },
fetchPolicy: 'cache-and-network',
});
So every time the visible map area changes (by the user), a new request is triggered and the React component renders two times:
a first time with { loading : true, data: [] }
a second time with { loading : false, data: [...some new data...] }
Now my question: is it possible that the old data in the query is still present in data while the new query is loading?
Something like:
a first time with { loading : true, data: [..data from previous query...] }
a second time with { loading : false, data: [...new data...] }
As I'm new to Apollo I'm not sure if I can solved it with apollo. I tried several fetchPolicies but none worked.

AnyChart JS: Network Graph Nodes Overlapped

Here I load the JSON file and plot them as network graph to visualize relationship between entity. The data has around 60 relationships and I plotted successfully with JavaScript code as follows:
fetch('data.json')
.then((response) => response.json())
.then((jsonData) => {
const dataSample = JSON.parse(jsonData);
const nodes = dataSample.relation.map((relation) => ({
id: relation.target_relation,
relation_type: relation.relation_type,
}));
nodes.push({
id: dataSample.party_source,
relation_type: '-',
});
const edges = dataSample.relation.map((relation) => ({
from: dataSample.party_source,
to: relation.target_relation,
relation_type: relation.relation_type,
}));
// graph data
const data = {
nodes,
edges,
};
const chart = anychart.graph(data);
// node configuration
const configNodes = chart.nodes();
configNodes.normal().height(20);
configNodes.hovered().height(25);
configNodes.tooltip().useHtml(true);
configNodes.tooltip().format(`Party ID: {%id}`);
// edge configuration
const configEdges = chart.edges();
configEdges.labels().enabled(true);
configEdges.labels().format('{%relation_type}');
configEdges.labels().fontSize(12);
configEdges.labels().fontColor('black');
configEdges.labels().fontWeight(500);
configEdges.tooltip().useHtml(true);
configEdges
.tooltip()
.format(`Party Source: {%from}<br>Party Target: {%to}`);
configEdges.arrows({
enabled: true,
size: 8,
});
configEdges.stroke({
color: '#7998FF',
thickness: '1.5',
});
chart.listen('mouseOver', function (e) {
// change the cursor style
document.body.style.cursor = 'pointer';
});
chart.listen('mouseOut', function (e) {
// set the default cursor style
document.body.style.cursor = 'auto';
});
// chart behaviour
chart.container('container');
chart.draw();
});
Unfortunately, I got each node on the network graph overlapped or not properly separated between nodes like picture below:
How to add spacing between nodes in order to avoid the overlapping, I have been searching on the documentation for the network graph, but not found any API function to perform that. Is it supposed to be a small sized data to produce a proper network graph?
Looking at their examples in this playground they are using this to influence the layout. Have you tried playing around with the iterationcount?
// set chart layout settings
chart.layout({ iterationCount: 0 });
Source
https://playground.anychart.com/gallery/src/Network_Graph/Radial_Graph

How to use async data for use with chart.js in ionic

I am calling some data in via an api for an ionic app I'm making. The data is being called asynchronously and I need to assign the data to different variables for use in a chart that gets presented to the user. I'm struggling to assign the data to a variable that I can then access from the function which creates the chart (I'm using chart.js). Initially I've been trying to grab a list of dates from the data for use as the X axis scale, just to get things working.
Been trying quite a few things and failing. I initially thought it was because my variable was block scoped, but now I think its an async issue. Been reading about promises for hours, but although I understand the concept I can't see away to apply it to my current code (presuming the issue is async! I'm a noob on a self teaching mission here).
So this the code which handles pulling in the data from the api
async getData() {
const loading = await this.loadingController.create({
message: 'Loading'
});
await loading.present();
this.api.getData()
.subscribe(res => {
console.log(res);
this.data1 = res[0];
loading.dismiss();
console.log(this.data1);
const datelabel = this.data1.result[1].date;
}, err => {
console.log(err);
loading.dismiss();
});
}
And this is the code which creates the chart
useAnotherOneWithWebpack() {
var ctx = (<any>document.getElementById('canvas-linechart')).getContext('2d');
console.log('GotData', this.datelabel); //just to see what data I've got here if any in the console
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
labels: this.datelabel,
datasets: [{
data: [86,114,106],
label: "Africa",
borderColor: "#3e95cd",
fill: false
}, {
data: [282,350,411],
label: "Asia",
borderColor: "#8e5ea2",
fill: false
}, {
data: [168,170,178],
label: "Europe",
borderColor: "#3cba9f",
fill: false
}
]
},
options: {
title: {
display: true,
text: 'World population per region (in millions)'
}
}
});
}
So I'm calling the datalabel variable against labels, but its displaying as undefined on the axis and in the console. I'm expecting to see three months (which are saved as strings in the variable). Tried all sorts now and its driving me a bit mad. I'm not even sure its an async issue, but from what I've done so far it feels like the issue.
Any help really appreciated!!
Not sure when/where you're calling the useAnotherOneWithWebpack() method but one issue from your code is that you're assigning some values to the local constant datelabel but not to the property from the component:
// The following line just creates a local const available only in that scope
const datelabel = this.data1.result[1].date;
Instead, you should be initializing the component's property:
this.datelabel = this.data1.result[1].date;
Keeping that in mind, please try the following:
async getData() {
const loading = await this.loadingController.create({
message: 'Loading'
});
await loading.present();
this.api.getData().subscribe(
res => {
// This line will be executed when getData finishes with a success response
console.log('Inside of the subscribe - success');
console.log(res);
this.data1 = res[0];
this.datelabel = this.data1.result[1].date;
// Now that the data is ready, you can build the chart
this.useAnotherOneWithWebpack();
loading.dismiss();
},
err => {
// This line will be executed when getData finishes with an error response
console.log('Inside of the subscribe - error');
console.log(err);
loading.dismiss();
});
// This line will be executed without waiting for the getData async method to be finished
console.log('Outside of the subscribe');
}

Real time application using ReactJS+ChartJS+SSE

I'm trying to build reactjs application. In this application I want to use chartjs to show line chart by subscribing the Server sent events(SSE).
I want to update line chart when there is new message from SSE. For that I've developed below code but the chart is not updating when there is new message. I'm printing the new message values in console and I can see those messages. But my chart is not updating on real-time bases.
for e.g if there is new message from SSE, the chart needs to be updated.
when I minimize my browser and maximize by browser that chart is updating with pulled messages values.
Once client connect to my server where SSE emit.
Please find screenshots here
Here is the code
let xAxis =[];
let yAxis=[];
class LineChartComponent extends Component
{
constructor(props) {
super(props);
this.state ={
data: []
}
this.eventSource = new EventSource('http://mydomainname:8090/kafka-messages');
}
componentWillMount() {
this.eventSource.onmessage = (e) => this.updateChart(JSON.parse(e.data));
}
updateChart(message){
let trgTS =message.TrgTS;
let value =parseFloat(100.0*message.Attributes[0].V/message.Attributes[1].V).toFixed(2);
xAxis.push(trgTS);
yAxis.push(value)
console.log(trgTS,value); // I can see the new messages values in console
this.setState(Object.assign({}, {
data: {
labels: xAxis,
datasets:[
{
label:'cycle time',
data: yAxis ,
fill: false,
borderColor: "#3cba9f"
}
]
}
}));
}
render()
{
return(
<div>
<Line data = {this.state.data} options = {{ maintainAspectRatio: false }} />
</div>
)
}
}

Dojo dGrid/dStore realtime update

I've been trying to get my dgrid/dstore grid in realtime.
As var as I understand the function 'Observable' is deprecated, and also it doesnt work for me.
I've tried to update the grid via a Interval timer but then the whole grid is erased and new loaded. How to update the whole grid 'inline' without erasing, and showing 'loading data'?
This is my basic code:
var timer = setInterval(function() {
store.invalidate(); // Invalidate the cache
store.fetch(); // Perform a new request for all items
grid.refresh();
}, 500);
Observable does not exist in dstore, but there is a Trackable mixin which can be used instead. As for updating the grid when new content is fetch from the store, you could use a dstore/Cache and then pass the cached Memory store that mixes in Trackable to the grid to use instead. Each time new data is added to the caching store, it will also be reflected in the grid.
require([
'dgrid/OnDemandGrid',
'dstore/Rest',
'dstore/Memory',
'dstore/Trackable',
'dstore/Cache',
'dojo/domReady!'
], function (OnDemandGrid, Rest, Memory, Trackable, Cache) {
var restStore = new Rest({
target: '/mockRequest/'
});
var store = Cache.create(restStore, {
cachingStore: new (Memory.createSubclass(Trackable))()
});
var grid = new OnDemandGrid({
collection: store.cachingStore,
columns: {
id: 'ID',
name: 'Name',
description: 'Description'
},
loadingMessage: 'Loading...'
}, 'main');
grid.startup();
setInterval(function () {
store.fetch();
}, 2000);
});

Categories