Skip to content

Instantly share code, notes, and snippets.

@BenSchZA
Created June 19, 2020 09:52
Show Gist options
  • Save BenSchZA/467040f154447bac07eb2bdb26834468 to your computer and use it in GitHub Desktop.
Save BenSchZA/467040f154447bac07eb2bdb26834468 to your computer and use it in GitHub Desktop.
Phoenix LiveView hooks with uPlot
{dates, counts} = CountByDateQuery.row_counts_by_date()
|> App.Repo.all()
|> Enum.with_index()
|> Enum.map(fn {{date, count}, index} ->
{:ok, date} = Timex.parse(date, "%b %Y", :strftime)
{Timex.to_unix(date), count}
end)
|> Enum.sort()
|> Enum.unzip()
chart_data = Poison.encode!([dates, counts]);
<div phx-hook="PhxChartComponent"
data-title="Failure rate"
data-xLabel="Time"
data-x="400"
data-yLabel="Count"
data-y="200"
data-data="{{ @chart_data }}">
<div id="chart" style="display: block;"></div>
</div>
Hooks.PhxChartComponent = {
updated() {
console.log('Updating chart')
let data = JSON.parse(this.el.dataset.data)
console.log(data)
this.chart.setData(data)
},
mounted() {
let data = [[],[]]
const opts = {
width: this.el.dataset.x,
height: this.el.dataset.y,
title: this.el.dataset.title,
cursor: true,
series: [
{
label: this.el.dataset.xLabel,
data: data[0],
},
{
label: this.el.dataset.yLabel,
data: data[1],
// scale: "%",
// value: v => v.toFixed(1) + "%",
color: "red",
width: 2,
// dash: [10, 5],
stroke: "red",
fill: "rgba(255,0,0,0.1)",
}
]
};
this.chart = new uPlot(opts, data, document.body)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment