(KeyError) key :abc not found in: %{conn: ...} (Chart.js)

Hi, I’m trying to connect chart.js with data in a database, so far no success. I think the problem might be somewhere in the assigns (Controller, index.html).

I’m still an elixir newbie.

My_error
(KeyError) key :abc not found in: %{conn: %Plug.Conn{adapter: {Plug.Cowboy.Conn, :...}, assigns: %{current_user: #MyApp.Users.User<__meta__: #Ecto.Schema.Metadata<:loaded, "users">, avatar: %{file_name: "48x48.png", updated_at: ~N[2022-09-29 12:23:30]}, bio: nil, business_creation: nil, companies: #Ecto.Association.NotLoaded<association :companies is not loaded>, country: nil, deleted_at: nil, email: "name@mail.com", email_confirmation_token: "02XXXX-XXXX-YYY-ZZZZ-ZZZZZ3d655", email_confirmed_at: nil, first_name: "Name", id: "02XXXX-XXXX-YYY-ZZZZ-ZZZZZ3d655", inserted_at: ~N[2022-09-29 12:23:16], invitation_accepted_at: nil, invitation_token: nil, invited_by: #Ecto.Association.NotLoaded<association :invited_by is not loaded>, invited_by_id: nil, invited_users: #Ecto.Association.NotLoaded<association :invited_users is not loaded>, last_name: "LName", phone_number: nil, position: "name@mail.com", private: false, programs: #Ecto.Association.NotLoaded<association :programs is not loaded>, region: nil, role: :role5, unconfirmed_email: nil, updated_at: ~N[2022-10-26 08:40:10], user_roles: [:role1, :role2, :role3, :role4, :role5], ...>, intercom: "", item_classification: [%MyApp.Srm.Itemclassification{__meta__: #Ecto.Schema.Metadata<:loaded, "item_classification">, **abc: "B"**, company_id: "02XXXX-XXXX-YYY-ZZZZ-ZZZZZ3d655, file_id: "02XXXX-XXXX-YYY-ZZZZ-ZZZZZ3d655", id: "02XXXX-XXXX-YYY-ZZZZ-ZZZZZ3d655", inserted_at: ~N[2022-11-04 10:28:17], item_id: "102000024", rsu: "S", updated_at: ~N[2022-11-04 10:28:17], xyz: "X"}

on the line: <span id="abcChartData" data-abc={"#{@abc}"} data-abc_counts={"#{@abc_count}"} />

_My_Code

Schema:

schema "item_classification" do
    field :abc, :string
    .
    .
    .
      def changeset(%Itemclassification{} = item_classification, attrs) do
    item_classification
    |> cast(attrs, [:company_id, :file_id, :item_id, :abc, :xyz, :rsu])
    |> validate_required([:company_id, :file_id, :item_id, :abc, :xyz, :rsu])
  end

  def abc_counts(query) do
    from i in Itemclassification,
    group_by: i.abc,
    select: %{i.abc => count(i.abc)}
  end

Context:

  alias PowerEngine.Srm.Itemclassification

  def abc_chart_data do
    Itemclassification
    |> Itemclassification.abc_counts
    |> Repo.all()
    |> Enum.sort()
    |> Enum.reduce(%{}, &Map.merge/2)
  end

Controller:

  def abc_chart(conn, _params) do
    abc_chart_data = Srm.abc_chart_data
    abc_counts = abc_chart_data |> Map.values() |> Poison.encode!()
    abc = abc_chart_data |> Map.keys() |> Poison.encode!()
    render(conn, "index.html", abc: abc, abc_counts: abc_counts) **#Is this correct?**
  end

Index.html:

<div>
  <canvas id="srmChart"></canvas>
  <span id="abcChartData" data-abc={"#{@abc}"} data-abc_counts={"#{@abc_count}"} /> **#Is this correct?**
</div>

JS_Code

app.js:

import SrmChart from "./srm_charts"
SrmChart.buildChart()

srma_chart.js:

import Chart from "chart.js"

let SrmChart = {
  buildChart() {
    let ctx = document.getElementById("srmChart"); 
    let abc = document.getElementById("abcChartData").dataset.abc;
    let counts = document.getElementById("abcChartData").dataset.abc_counts;
    let chart = new Chart(ctx, { 
    type: 'bar',
    data: {
      labels: console.log( JSON.parse(abc)),
      datasets: [{
        label: '# of ABC',
        data: console.log( JSON.parse(counts)),
        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)'
        ]
      }]
    },
    options: {
      scales: {
        yAxes: [{
          ticks: {
            beginAtZero: true
          }
        }]
      }
    }
  });
}
}
export default SrmChart

Thanks for any help.
:slight_smile:

what is your route look like in the router?

1 Like

@John_Shelby did you edit the error message or is your key actually abc? Usually the error you’re showing happens when you are referencing an assign that isn’t set.

2 Likes

resources "/srm_charts", SrmChartController

Controller:
defmodule "MyApp".SrmChartController

@benwilson512 I edited the IDs, name, email and so on in the error message, but abc is the original name.

@CherryPoppins @benwilson512 Got it, you got me moving in the right direction.
I had the wrong function name in the controller. I wanted to send it to index.html and had it instead of index in abc_chart. Thank you very much for your help and answers.

1 Like