1+ import React , { useContext } from 'react' ;
2+ // You can change the chart property imported to the one that suits your needs.
3+ import { Bar } from 'react-chartjs-2' ;
4+ import HealthContext from '../context/DetailsContext' ;
5+
6+ const MemoryChart = ( ) => {
7+ // ! Do not change the variables related to context.
8+ const healthData = useContext ( HealthContext ) ;
9+ const health = healthData . detailsData ;
10+
11+ // Helper function
12+ const createChart = ( ) => {
13+ // Object for storing data
14+ const memoryObj = {
15+ free : 0 ,
16+ active : 0 ,
17+ used : 0 ,
18+ total : 0
19+ } ;
20+
21+ // Iterate through HealthInfo to creat an object with data needed to create your graph.
22+ for ( let i = 0 ; i < health . length ; i += 1 ) {
23+ //Mongo
24+ if ( health [ i ] . freeMemory ) {
25+ memoryObj . free += health [ i ] . freeMemory
26+ memoryObj . active += health [ i ] . activeMemory
27+ memoryObj . used += health [ i ] . usedMemory
28+ memoryObj . total += health [ i ] . totalMemory
29+ } else if ( health [ i ] . freememory ) {
30+ memoryObj . free += health [ i ] . freememory ;
31+ memoryObj . active += health [ i ] . activememory ;
32+ memoryObj . used += health [ i ] . usedmemory ;
33+ memoryObj . total += health [ i ] . totalmemory ;
34+ }
35+ }
36+ memoryObj . free /= 1000000000
37+ memoryObj . active /= 1000000000
38+ memoryObj . used /= 1000000000
39+ memoryObj . total /= 100000000
40+
41+ // ! Chart Data
42+ // * --- Change the object used in data to the one you created.
43+ // * --- Labels must be in the same order as the keys in your object.
44+ const chartData = {
45+ datasets : [
46+ {
47+ label : 'Breakdown of Memory in Gigabytes' ,
48+ data : Object . values ( memoryObj ) ,
49+ backgroundColor : [
50+ 'rgb(2, 210, 249)' ,
51+ 'rgb(198, 42, 177)' ,
52+ 'rgb(252, 170, 52)' ,
53+ 'rgb(239, 91, 145)' ,
54+ 'rgb(182, 219, 26)' ,
55+ 'rgb(254, 255, 0)' ,
56+ ] ,
57+ } ,
58+ ] ,
59+ labels : [ 'Free Memory' , 'Active Memory' , 'Used Memory' , 'Total Memory' ] ,
60+ } ;
61+
62+ return < Bar data = { chartData } /> ;
63+ } ;
64+
65+ // Return div with helper function invoked
66+ return < div > { createChart ( ) } </ div > ;
67+ } ;
68+
69+ export default MemoryChart ;
0 commit comments