What could be causing the strange output from my filtered Object.values() function?

In my Vue3 component, I created a feature to showcase data using chips. The input is an Object with keys as indexes and values containing the element to be displayed.

Here is the complete code documentation:

<template>
  <div class="row">
    <div>a fixed entry during debug</div>
    <q-chip v-for="alert in failedAlerts" :key="alert.Id" color="orange">{{ alert.FullTargetName }}</q-chip>
  </div>
</template>

<script lang="ts">

import {toRef, Ref, computed, watch} from 'vue'
import log from 'assets/log'

interface Alert {
  IsOK: boolean;
  FullTargetName: string,
  Why: string,
  Extra: string,
  Id: string,
  When: string
}

function alertFactory(): Alert {
  return {
    Extra: '', FullTargetName: 'dummy alert', Id: '0', IsOK: false, When: '0', Why: 'dummy alert explanation',
  }
}

export default {
  name: 'Homemonitor',
  // the complete props definitiin is temporarily commented out to make sure the problem
  // does not come from here
  // props: {
  //   alerts: {
  //     type: Object,
  //     default: () => alertFactory(),
  //   },
  // },
  props: ['alerts'],
  setup(props) {
    // TODO: review the global eslint exclusions below
    /* eslint-disable @typescript-eslint/no-unsafe-call */
    /* eslint-disable @typescript-eslint/no-unsafe-return */
    /* eslint-disable @typescript-eslint/no-unsafe-member-access */

    let failedAlerts = computed(() => Object.values(toRef(props, 'alerts')).filter((x: Alert) => !x.IsOK))

    return {failedAlerts}
  },
}
</script>

<style scoped>

</style>

Upon inspecting DevTools → Vue, I noticed that failedAlerts wasn't the expected neat Array of Alert, but rather

alert in both props and setup → failedAlerts → alerts` contains the correct content

The issue arises because Object.values() should have returned an Array of values from the object (filtered).

Based on the provided data, it should look something like this: (IsOK being true would filter it out)

// failedAlerts

[
  {
    "IsOK":true,
    "FullTargetName":"bind → Amazon_Fire",
    "Why":"",
    "Extra":"",
    "Id":"8bd3b2c7fe73ea6c0d0aac324baaa354",
    "When":"2021-08-19T13:02:33+02:00"
  },
(...)
]

What could be causing failedAlerts to have the current structure?


UPDATE: After carefully examining the types in my code (thanks to @EstusFlask for the help), I believe I have resolved the issues in the <script> section.

<script lang="ts">

import {computed, Ref, toRef, watch} from 'vue'

interface Alert {
  IsOK: boolean;
  FullTargetName: string,
  Why: string,
  Extra: string,
  Id: string,
  When: string
}

function alertFactory(): Record<string, Alert> {
  return {
    'dummy index':
        {
          Extra: '', FullTargetName: 'dummy alert', Id: '0', IsOK: false, When: '0', Why: 'dummy alert explanation',
        },
  }
}

export default {
  name: 'Homemonitor',
  props: {
    alerts: {
      type: Object,
      required: true,
      // default: () => alertFactory(),
    },
  },
  // props: ['alerts'],
  setup(props) {
    // TODO: review the global eslint exclusions below
    /* eslint-disable @typescript-eslint/no-unsafe-call */
    /* eslint-disable @typescript-eslint/no-unsafe-return */
    /* eslint-disable @typescript-eslint/no-unsafe-member-access */

    let failedAlerts = computed(() => Object.values(props.alerts as Ref<Record<string, Alert>>).filter((x: Alert) => !x.IsOK))

    return {failedAlerts}
  },
}
</script>

Answer №1

toRef retrieves a reference of the specified type

interface Ref<T> {
  value: T
}

When Object.values is applied to this reference, it returns an array containing the values of that type.

To access the actual values stored within the object, utilize toRef(...).values.

Given that props.alert is reactive by default, implementing toRef may not be necessary (as others have also pointed out). Instead, consider using Object.values(props.alerts)

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

Utilizing i18next for both a custom Typescript library and a host simultaneously: a step-by-step guide

Currently, I am in the process of developing a typescript library that is designed to take in an object and generate an excel file. This library is intended for use with multiple React applications. Each React application, or host, will provide its own obj ...

Utilizing an array to pass a series of items to a function parameter

I am currently working on an Angular project that involves a controller and service. In this setup, the controller sends data and an endpoint to the service. As of now, the service handles the http request. However, I am in the process of refactoring my ...

Dealing with ParseInt NaN problems in your code: a comprehensive guide

I have a code where I am trying to calculate the sum of input values. It works fine when numbers are entered, but if any input field is cleared, it shows total as NaN. I understand that using parseInt for number value is causing this issue, but without usi ...

Ways to resolve issues related to null type checking in TypeScript

I am encountering an issue with a property that can be null in my code. Even though I check for the value not being null and being an array before adding a new value to it, the type checker still considers the value as potentially null. Can anyone shed lig ...

The POST function is executed twice, with the first attempt resulting in a failed API call, but the second attempt is

I am experiencing issues with my subscribe dialog, as it seems to be running the API call twice. The first time it fails, but on the second attempt, it succeeds and inserts the email into the database. This double run is causing errors in my AJAX function, ...

Utilizing the current state within a React callback function closure: A guide to maximising efficiency

I'm currently working on a web page that features a dynamic list of form inputs. Users have the ability to add or remove input fields using designated buttons. To manage this functionality, I've created a parent object called <Ingredients /> ...

I'm encountering a "confirm" error within the data table. Any suggestions on how to resolve this issue?

When I try to use two datatables columns in confirm, an error occurs when the text 'do you want cancel?' is displayed. The issue seems to be with the text itself and not the code. How should we go about fixing this problem? This is my current cod ...

Searching for an object in Vue 3 Composition API and displaying its contents

Experiencing a challenge with my first Vue.js project, seeking assistance in resolving the issue. Upon receiving a response from my API, I retrieve a list of projects and aim to locate the one matching the ID provided in the URL parameter. A peculiar error ...

The user could not be deserialized from the session

I am having an issue with deleting users from my database. When a user is logged in and I try to refresh the page after deleting the user, I encounter the following error message: Error: Failed to deserialize user out of session Below is the code snippet ...

Zoom out the slider when scrolling

Take a look at this link and as you scroll down the page, notice how the image transitions to iPhone. Can anyone provide insight on how this effect is achieved? ...

Rendering Vue components synchronously as a singular string

There exists a Vue SFC called Bubble, which contains a simple layout structure. Bubble.vue <script setup lang="ts"> </script> <template> <div hinted-name="wrapper-bubble" class="hinted-bubble-wrapper" ...

The express route parser is incorrectly detecting routes that it should not

I am encountering an issue with the following two routes: router.get('/:postId([0-9]*)', handler) router.get('/:postId([0-9]*)/like', handler) The first route is intended to only capture URLs like /posts/4352/, not /posts/3422/like. ...

Utilizing v-model for dynamic binding within a v-for iteration

I'm currently working on binding v-model dynamically to an object property within an array of objects. I am unsure about how to accomplish this task. The objective is to choose a user using the Select HTML tag and then display the list of that user&ap ...

The structure of a project using a Vue app and a Node API

Seeking your thoughts on combining a Vue App with a Node using API for my upcoming project. I have set up two separate folders for the client (VueJs) and server (Node) locally: - client (VueJs) - server (Node) I am currently running them individually usi ...

"pre and post" historical context

Is there a way to create a stunning "Before and After" effect using full-sized background images? It would be amazing if I could achieve this! I've been experimenting with different examples but can't seem to get the second 'reveal' di ...

Transforming ajax code into node.js

After mastering ajax calls for client-server interaction, I am facing a challenge in converting my code to a server-side node compatible JS using http requests. Despite reading various tutorials, I am struggling to adapt them to fit with my current code st ...

The manipulation of the DOM is not possible within the AJAX success function

I'm curious about the issue I am facing with changing the 'this' element on AJAX success. Despite my efforts to switch classes and add a new data attribute to the anchor tag in ajax success, it doesn't seem to be working. Interestingly, ...

Deciphering unidentified Json data

Having some trouble with an error in my note taker app built using expressjs. Everything was working fine until I tried to save a new note and it's throwing this error: SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse () Here&apos ...

What is the process for defining the host in a websocket connection?

When working on my page, I establish a websocket connection to the server using ws://127.0.0.1:5000/ws in development and ws://www.mymachine.com/ws when deployed to production. Is there a more efficient way to handle this so that I don't have to manua ...

Customize the appearance of disabled dates in the eonasdan-datetimepicker styling

I am seeking to customize the default styles for the "eonasdan-datetimepicker" (https://github.com/Eonasdan/bootstrap-datetimepicker) by implementing a basic hover message feature. The CSS attributes currently applied to disabled dates are as follows: .bo ...