[SOLVED] in svelte using getter with Object.values() “Maximum call stack size exceeded”

Issue

This Content is from Stack Overflow. Question asked by stackdeveloper

I am using the svelte.js framework

enter image description here

and I am using a function that returns an object like this {x, y, rotated, isMoving}

the problem is that isMoving use getter

{
  get isMoving() {
    return Object.values(this)
  }
}

basically I want all the values to be in a array and then loop on it.


function activeAxis() {
  return {
    x: x !== prevCoords.x && y === prevCoords.y,
    y: y !== prevCoords.y && x === prevCoords.x,
    rotated: y !== prevCoords.y && x !== prevCoords.x,
    get isMoving() {
      return Object.values(this)
    }
  };
}

the array is a series of points with x and y

like this:

let array = [{
    x: 10
    y: 20
  },
  {
    x: 15
    y: 20
  },
  {
    x: 25,
    y: 9
  },
  {
    x: 25,
    y: 30
  },
  {
    x: 25,
    y: 25
  },
  {
    x: 25
    y: 25
  }
]

here my 2 components

Canvas.svelte

<script>
  import Gline from "./Gline.svelte";

  let coordsArray = [];

  for (let i = 0; i < 20; i++) {
    coordsArray = [
      ...coordsArray,
      {
        x: 10,
        y: i * 10,
      },
    ];
  }
</script>

<div>
  {#each coordsArray as thisCoords, index}
    {@const prevCoords = coordsArray[index - 1]
      ? coordsArray[index - 1]
      : coordsArray[index]}
    <Gline x={thisCoords.x} y={thisCoords.y} {prevCoords} />
  {/each}
</div>

Line.svelte

<script>
  export let x;
  export let y;
  export let prevCoords;

  function activeAxis() {
    return {
      x: x !== prevCoords.x && y === prevCoords.y,
      y: y !== prevCoords.y && x === prevCoords.x,
      rotated: y !== prevCoords.y && x !== prevCoords.x,
      get isMoving() {
        return Object.values(this)
      }
    };
  }

  console.log(activeAxis().isMoving);
</script>

<div class="h-1 bg-cyan-500 absolute w-28" style="top: {y}px; left: {x}px;" />



Solution

  1. It’s not related to svelte
  2. By calling Object.values(this) in a getter you are calling this getter in a loop and never return an actual value.
  3. Just don’t do this

Better use one of these:

function activeAxis() {
  return {
    x: x !== prevCoords.x && y === prevCoords.y,
    y: y !== prevCoords.y && x === prevCoords.x,
    rotated: y !== prevCoords.y && x !== prevCoords.x,
  };
}

console.log(Object.values(activeAxis())
function activeAxis() {
  return {
    x: x !== prevCoords.x && y === prevCoords.y,
    y: y !== prevCoords.y && x === prevCoords.x,
    rotated: y !== prevCoords.y && x !== prevCoords.x,
    isMoving() {
      return Object.values(this)
    }
  };
}

console.log(activeAxis().isMoving())


This Question was asked in StackOverflow by stackdeveloper and Answered by Konrad Linkowski It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?