Вот мой код, который отображает мои данные на гистограмме с помощью библиотеки chart. js. Я использовал эту библиотеку в перехватчиках реакции, useEffect. Вот мой код DailyTrafficCard и DailyTrafficCardContainer:
import React, { useEffect } from 'react';
import Chart from 'chart.js';
import { Card } from 'components/Card';
import { localDateTime, dateFilter } from 'helpers';
const red = '#644DFF';
const purple = '#F73F64';
const DailyTrafficCard = (props) => {
const { store, capacity, data, setVar} = props;
const lastSevenDays = Array(7)
.fill()
.map((_, i) => {
const localdate = localDateTime(store);
return localdate()
.subtract(i, 'day')
.format('YYYY-MM-DD[T]07:00:00[Z]');
});
//console.log('lastSevenDays',lastSevenDays);
useEffect(() => {
const ctx = document && document.querySelector('#daily-traffic-chart');
if (!ctx) {
return;
}
//console.log('previous data sent here',data);
/*if (data.length>1 ){
data.shift();
}*/
//console.log('after change date sent here',data)
console.log('data sent here is',data);
const bar = new Chart(ctx, {
type: 'bar',
data: {
labels: [],
datasets: [{
data: data[0],
barThickness: 13,
backgroundColor: (ctx) => {
const idx = ctx && ctx.dataIndex;
const val = ctx && ctx.dataset && ctx.dataset.data && ctx.dataset.data[idx];
return val < 40 ? purple : red;
}
}]
},
options: {
//events:[],
intersect: false,
legend: {
display: false,
},
scales: {
xAxes: [{
type: 'time',
offset: true,
time: {
unit: 'hour',
displayFormats: {
hour: 'HH',
},
},
ticks: {},
gridLines: {
display: false,
},
}],
yAxes: [{
gridLines: {
display: true,
},
ticks: {
beginAtZero: true,
min: 0,
max: capacity,
stepSize: 5
},
}],
},
}
});
}, [data,capacity]);
const handleOnChange = (event) => {
setVar(event.target.value);
}
return (
<Card
classname="DailyTrafficCard"
icon={<span><i className="icon-user"/></span>}
title={<h3>Daily Traffic Analytics</h3>}>
<div className="daily">
<div className="daily-head p-4 text-center">
<select className="py-2 px-3" onChange={handleOnChange}>
{lastSevenDays.map(date => (
<option key={date} value={date}>{dateFilter(date, 'dddd')}</option>
))}
</select>
</div>
<div className="px-8">
{data && data.length > 0 && (
<canvas width="250" id="daily-traffic-chart"></canvas>
)}
</div>
</div>
</Card>
)
}
export {
DailyTrafficCard
}
import React, { useContext, useEffect, useState } from 'react';
import { AppContext } from 'contexts/App';
import { DailyTrafficCard } from './DailyTrafficCard';
import { API_URL } from 'constants/index.js';
import moment from 'moment';
const DailyTrafficCardContainer = (props) => {
const { API } = useContext(AppContext);
const { store } = props;
const [data, setData] = useState([]);
const [myVar, setMyVar] = useState(moment().format('YYYY-MM-DD[T]07:00:00[Z]'));
const setVar = (value) => {
setMyVar(value);
}
//console.log('start time is',myVar)
//const [start,setStart] = useState(null);
//const [end,setEnd] = useState(null);
var start = myVar;
var end = moment(start).add(21,'hours').format('YYYY-MM-DD[T]HH:mm:ss[Z]');
//setStart(myVar);
//etEnd(moment(myVar).add(18,'hours').format('YYYY-MM-DD[T]HH:mm:ss[Z]'));
//console.log('start time is',start,'end time is',end);
useEffect(() => {
async function fetchData() {
console.log('start is',start);
console.log('end is',end);
const result = await API.get(`${API_URL}/api/aggregates`, {
params: {
//want it to be specific days
start,
end,
every: '1h',
},
});
console.log('what is result?',result);
setData([
result && result.data && result.data.map(({ time, In, Out }) => ({
x: time,
/*moment(time)
.tz(store.timezone)
.add(13,'hours')
.format('YYYY-MM-DD[T]HH:mm:ss[Z]')*/
y: In - Out
}))
])
console.log('data before sent to Card is',data);
/*if (data.length>1 ){
data.shift();
}*/
//console.log('data in container',data)
;
}
fetchData();
/*const interval = setInterval(() => {
fetchData();
}, 5000);*/
/*return () => {
clearInterval(interval);
};*/
}, [myVar]);
return <DailyTrafficCard {...props} data={data} setVar={setVar}/>
}
export {
DailyTrafficCardContainer
}
Проблемы: символ времени, отмеченного на оси x, и данные в гистограмме не соответствуют времени на оси, как показано на рисунке: введите описание изображения здесь