d3.js/Typescript Error: The attribute <path> d has encountered an issue. It was expecting a moveto path command ('M' or 'm') but instead received "function line(da…"

Exploring d3.js for the first time, I am attempting to convert the data visualization rules outlined in this guide to work with vue3 and typescript.

Below you will find the code snippet I have been working on:

<template>
  <svg
    class="line-chart"
    :viewBox="viewBox"
  >
    <g transform="translate(0, 10)">
      <path
        class="line-chart__line"
        :d="path(data)"
      />
    </g>
  </svg>
 </template>


<script lang="ts">
import { ref, defineComponent, computed, toRef } from 'vue';
import * as d3 from 'd3';
export default defineComponent({
  name: "StandardMetric",
  props: {
    data: {
      required: true,
      type: Array,
    },
    width: {
      default: 500,
      type: Number,
    },
    height: {
      default: 270,
      type: Number,
    },
  },
  setup(props){
        const padding = 60;

        const data = [99, 71, 78, 25, 36, 92];

       const rangeY = computed(() => {
        const defaultHeight: number =props.height?props.height:270;
        const height: number = defaultHeight - padding;
        return [0, height];
      });
      
      const rangeX = computed(() => {
        const defaultWidth: number =props.width?props.width:500;
        const width: number = defaultWidth - padding;
        return [0, width];
      });

      
      const path =(linedata: number[])=> {

    
      const maxIndex: number = linedata.length-1;
  
      let maxValue = d3.max(linedata);
      maxValue = maxValue?maxValue:0
      const x = d3.scaleLinear().range(rangeX.value).domain([0, maxIndex]);
      const y = d3.scaleLinear().range(rangeY.value).domain([0, maxValue]);

      d3.axisLeft(x);
      d3.axisTop(y);

      // return d3.line<ChartData>()
      //    .x((d:ChartData, i) => x(i))
      //   // .x(d=>x(d))
      //   .y((d:ChartData) => y(d.p));
       return d3.line<number>()
              .x((d, i)=>x(i))
              .y(d=>y(d))
     }

     const line = computed(()=> {
       return path(data)
     })

     const viewBox = computed(() =>{
      return `0 0 ${props.width} ${props.height}`;
    })

     return {
       line,
       viewBox,
       path,
       data
     }


  }
}
)
</script>

Upon loading the page, I encountered the following error:

Error: <path> attribute d: Expected moveto path command ('M' or 'm'), "function line(da…". More details...

I have included the package.json content below:

{
  "name": "tools-ui",
  "version": "0.0.0",
  "scripts": {
    "dev": "vite",
    "build": "vue-tsc --noEmit && vite build",
    "serve": "vite preview"
  },
  "dependencies": {
    "@types/d3": "^6.3.0",
    "d3": "^6.6.2",
    "element-plus": "^1.0.2-beta.36",
    "vue": "^3.0.5",
    "vue-router": "^4.0.5",
    "vuex": "^4.0.0"
  },
  "devDependencies": {
    "@typescript-eslint/eslint-plugin": "^4.20.0",
    "@typescript-eslint/parser": "^4.20.0",
    "@vitejs/plugin-vue": "^1.2.1",
    "@vue/compiler-sfc": "^3.0.5",
    "eslint": "^7.23.0",
    "eslint-config-prettier": "^8.1.0",
    "eslint-plugin-prettier": "^3.3.1",
    "eslint-plugin-vue": "^7.8.0",
    "prettier": "^2.2.1",
    "typescript": "^4.1.3",
    "vite": "^2.1.5",
    "vue-tsc": "^0.0.15"
  }
}

I suspect there may be an issue with my path function, but I am unable to pinpoint the exact problem. Any assistance would be greatly appreciated. Thank you!

Answer №1

After some exploration, I have uncovered the following crucial details:

  1. The path function must precisely define the "method to determine the path"
  2. The line function should be calculated and ought to utilize a function derived from the path function, followed by using the data. Here is the refined version that works smoothly:
<template>
  <svg
    class="line-chart"
    :viewBox="viewBox"
  >
    <g transform="translate(0, 10)">
      <path
        class="line-chart__line"
        :d="line"
      />
    </g>
  </svg>
 </template>


<script lang="ts">
import { ref, defineComponent,computed, toRef } from 'vue';
import * as d3 from 'd3';
export default defineComponent({
  name: "StandardMetric",
  props: {
    data: {
      required: true,
      type: Array,
    },
    width: {
      default: 500,
      type: Number,
    },
    height: {
      default: 270,
      type: Number,
    },
  },
  setup(props){
        const padding = 60;

        const data = [99, 71, 78, 25, 36, 92];

       const rangeY = computed(() => {
        const defaultHeight: number =props.height?props.height:270;
        const height: number = defaultHeight - padding;
        return [0, height];
      });
      
      const rangeX = computed(() => {
        const defaultWidth: number =props.width?props.width:500;
        const width: number = defaultWidth - padding;
        return [0, width];
      });

      
      const path =()=> {

    
      const maxIndex: number = data.length-1;
  
      let maxValue = d3.max(data);
      maxValue = maxValue?maxValue:0
      const x = d3.scaleLinear().range(rangeX.value).domain([0, maxIndex]);
      const y = d3.scaleLinear().range(rangeY.value).domain([0, maxValue]);

      d3.axisLeft(x);
      d3.axisTop(y);

      return d3.line<number>()
              .x((d, i)=>x(i))
              .y(d=>y(d))
     }

     const line = computed(()=> {
       const pathFunc = path()
       return pathFunc(data)
     })

     const viewBox = computed(() =>{
      return `0 0 ${props.width} ${props.height}`;
    })

     return {
       line,
       viewBox,
  
     }


  }
}
)
</script>
<p>Let's hope this updated version proves beneficial for someone in need in the future</p>
    </div></answer1>
<exanswer1><div class="answer" i="66952683" l="4.0" c="1617613118" a="R2luZ2VyX0NoYWNoYQ==" ai="11663956">
<p>Ah, now the mystery has been unlocked - behold, the secrets lie within:</p>
<ol>
<li>The Path function is expected to yield the "definition of how to trace the path"</li>
<li>The Line function requires careful computation and implementation of a function obtained from the Path function in order to operate effectively. Check out the functional version below:</li>
</ol>
<pre><code><template>
  <svg
    class="line-chart"
    :viewBox="viewBox"
  >
    <g transform="translate(0, 10)">
      <path
        class="line-chart__line"
        :d="line"
      />
    </g>
  </svg>
 </template>


<script lang="ts">
import { ref, defineComponent,computed, toRef } from 'vue';
import * as d3 from 'd3';
export default defineComponent({
  name: "StandardMetric",
  props: {
    data: {
      required: true,
      type: Array,
    },
    width: {
      default: 500,
      type: Number,
    },
    height: {
      default: 270,
      type: Number,
    },
  },
  setup(props){
        const padding = 60;

        const data = [99, 71, 78, 25, 36, 92];

       const rangeY = computed(() => {
        const defaultHeight: number =props.height?props.height:270;
        const height: number = defaultHeight - padding;
        return [0, height];
      });
      
      const rangeX = computed(() => {
        const defaultWidth: number =props.width?props.width:500;
        const width: number = defaultWidth - padding;
        return [0, width];
      });

      
      const path =()=> {

    
      const maxIndex: number = data.length-1;
  
      let maxValue = d3.max(data);
      maxValue = maxValue?maxValue:0
      const x = d3.scaleLinear().range(rangeX.value).domain([0, maxIndex]);
      const y = d3.scaleLinear().range(rangeY.value).domain([0, maxValue]);

      d3.axisLeft(x);
      d3.axisTop(y);

      return d3.line<number>()
              .x((d, i)=>x(i))
              .y(d=>y(d))
     }

     const line = computed(()=> {
       const pathFunc = path()
       return pathFunc(data)
     })

     const viewBox = computed(() =>{
      return `0 0 ${props.width} ${props.height}`;
    })

     return {
       line,
       viewBox,
  
     }


  }
}
)
</script>

May this enlightenment serve as a beacon of guidance for those seeking answers down the road

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The 'innerText' property is not found in the 'Element' type

Currently, I am working with Typescript and Puppeteer. My goal is to extract the innerText from an element. const data = await page.$eval(selector, node => node.innerText); However, I encountered an error: The property 'innerText' is not ...

When working with Visual Studio and a shared TypeScript library, you may encounter the error message TS6059 stating that the file is not under the 'rootDir'. The 'rootDir' is expected to contain all source files

In our current setup with Visual Studio 2017, we are working on two separate web projects that need to share some React components built with TypeScript. In addition, there are common JavaScript and CSS files that need to be shared. To achieve this, we hav ...

How to update the page title in React TypeScript 16.8 without using Helmet

I have created a custom 404 not found page, and I would like the title of the page to change when someone navigates to it. Unfortunately, I do not want to use Helmet for this purpose, but I am struggling to make constructor or componentDidMount() work in ...

Combine all Typescript files into one JavaScript file without any extra steps

I'm fairly new to Typescript and I'm excited to use it for an upcoming JavaScript project. The modularity features that Typescript provides will make maintaining and developing the project much easier. I've organized each class in its own ts ...

Issue with Cypress TypeScript: Unable to locate @angular/core module in my React application

I am currently in the process of updating my Cypress version from 9.70 to 10.7.0. Although I have fixed almost all the bugs, I have encountered a strange message stating that @angular/core or its corresponding type declarations cannot be found. My applica ...

The failure to import a node module in next.js with typescript

I'm currently working on integrating a package called bcrypt into my project. I have successfully installed it using npm install bcrypt. Although the package is visible in the node_modules folder, I am encountering an error when trying to import it i ...

Is the spread operator in React failing to function as anticipated?

In my current project, I encountered an issue while trying to pass a GeolocationCoordinates object to a child component using the spread operator. Strangely, in the child props, it appears as an empty object: interface HUDState { geoCoords: Geolocation ...

Instructions on how to dynamically show specific text within a reusable component by utilizing React and JavaScript

My goal is to conditionally display text in a reusable component using React and JavaScript. I have a Bar component that I use in multiple other components. In one particular ParentComponent, the requirement is to show limit/total instead of percentage va ...

Exporting declarations and different export types within a TypeScript ambient module

I am currently working on adding specific types for the config module in our application. The config module is generated dynamically from a JSON file, making it challenging to type. Since it is a node module, I am utilizing an ambient module for the typing ...

I'm encountering a 404 error on Next.js localhost:3000

Embarking on a fresh project in Next.js, my folder structure looks like this: https://i.stack.imgur.com/HhiJo.png However, upon navigating to localhost:3000, I am greeted with a 404 error screen. It seems there is an issue with the routing, but unfortuna ...

There is no mistake when using a value that falls outside of a TypeScript

Expecting to encounter a compile time error with this code, but it seems my understanding of enums is off... enum SortDirection { ascending = 1, descending = -1 } type IndexSpec = {[index: string]: SortDirection}; var i: IndexSpec = {thing: 3}; ...

Error: The property 'template' is not defined and cannot be read

https://i.sstatic.net/G5QPW.png Data table not loading properly ** JavaScript code ** displayedColumns = ['bloodpressure', 'username', 'weight', 'height']; @ViewChild(MatPaginator) paginator: MatPaginator; ...

Solving runtime JavaScript attribute issues by deciphering TypeScript compiler notifications

Here is a code snippet I am currently working with: <div class="authentication-validation-message-container"> <ng-container *ngIf="email.invalid && (email.dirty || email.touched)"> <div class="validation-error-message" *ngIf=" ...

angular-tree-component | fetch Path

Can someone help me figure out how to retrieve the full path when clicking on a node? I noticed there is a path option in the API, but I'm unsure of how to incorporate it with the click event. options: ITreeOptions = { actionMapping: { mouse: { ...

Integrate a dynamic component into the Angular 7 template

The code I am working with currently has a scenario where during the ngOnInit() execution, the correct component is stored in this.widget, along with appropriate data in this.data. I encountered difficulty trying to smoothly integrate the dynamic componen ...

What is the best way to implement a switch case for the value of a property within an object in a TypeScript file?

The object I'm dealing with looks like this: {a: auth?.type === '1' || auth?.type === '2' || auth?.type === '3' ? { reason: // I need to implement a switch case here : un ...

No signature match found for 'new (): XXX' within 'XXX'

I encountered an issue while using the following class and receiving a specific error within the for loop: [ts] Argument of type 'Component' is not assignable to parameter of type 'ComponentType'. Type 'Component' pro ...

Unable to loop through the Array

let Users = [ { name: 'John', id: '1', jp: 'USA' }, { name: 'Jane', id: '2', jp: 'Japan' }, ]; export function DisplayUsers(usersList) { return ( <div> {usersList?.map((user ...

After each save, gulp-typescript is emitting errors, however, it works without any issues upon subsequent saves

I'm facing some uncertainty regarding whether the issue I'm encountering is related to gulp, typescript, or Angular 2. Currently, I am using Angular 2 Beta 6. Here is an example of my typescript gulp task: var tsProject = p.typescript.createPr ...

When ngIf fails to detect a change in a variable's value

Whenever I try to set a simple boolean variable to show/hide a div from another component, the ngIf directive doesn't seem to recognize it. In my messages-refresh.component.html file: <div class="divOpacity" *ngIf="show"> <div class="boxMes ...