Hello,
I created a chart with chart.js to display some data from the application I am working on and I wanted it to update in real time to reflect the changes in the data so I created a chart channel and a socket, but I can’t figure out why it is not working… I’ve been following the guide on elixircast.io and tried to contact the author as well but no reply sofar so I thought I would ask the question here
so in user_socket.ex I added the channel like so:
channel "chart:*", Assistant.Web.ChartChannel
in chart_channel.ex i modified the generated join function:
def join("chart:title", _payload, socket) do
{:ok, socket}
end
in app.js I imported the socket and passed in into my buildChart function:
import socket from “./socket”;
let patientChartElement = document.getElementById("patientChart")
patientChartElement && PatientChart.buildChart(socket);
finally in patient_chart.js i created the chart and added the socket:
import Chart from "chart.js";
let PatientChart = {
buildChart(socket) {
var ctx = document.getElementById("patientChart").getContext('2d');
let patients = document.getElementById("patientChartData").dataset.patients;
let patients_count = document.getElementById("patientChartData").dataset.count;
let PatientChart = new Chart(ctx, {
type: 'bar',
data: {
labels: JSON.parse(patients),
datasets: [{
label: '# of Patients by Gender',
data: JSON.parse(patients_count),
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
this.listenForUpdates(socket, chart);
},
listenForUpdates(socket, chart){
let channel = socket.channel("chart:title", {});
channel.join()
.receive("ok", resp => { console.log("Joined successfully", resp) })
.receive("error", resp => { console.log("Unable to join", resp) })
channel.on("new_patient", payload => {
chart.data.dataset.forEach((dataset) => {
dataset.data = JSON.parse(payload.body);
});
chart.update();
});
}
};
export default PatientChart;
supposidely when loading the page I should see a console log saying channel joined succesfully or the error but i get nothing… and the chart does not update unless I reload the page.
Probably is something extremely silly but I can’t figure it out
Anyhow thanks as always for the help you are all awesome
-Carlo