Error loading data in the Lit-Element component update-element.js

Here is a snippet of code that I am currently working on:

import {LitElement, html} from '@polymer/lit-element';
import {SdkArticle} from '../elements/sdk-article/sdk-article.js'

class PraksisView extends LitElement {

    static get properties() {
        return {
            articles: {type: Array},
        };
    }

    constructor() {
        super();
        this.articles = [];
    }

    async firstUpdated() {
        await fetch(`/testData.json`)
            .then(r => r.json())
            .then(async data => {
                this.articles = data.articles;
            });
    }


    render() {
        return html `
          <style>
     .indent-1 {float: left;}
    .indent-1 section {width: 50%; float: left;}
        header {
            display: block;
            height: 50px;
            background-color: #215959;
            color: white;
        }
        .center {
  margin: auto;
  padding-top: 10px;
  padding-bottom: 10px;
  padding-left: 50px;
}
        </style>
        <header>
            <h3 class="center">Almen praksis</h3>
        </header>  
        <section class="indent-1">
            <section>                
                <div>
                    <ul>
                        <li>Patientbehandling</li>
                        <li>Klinikdrift</li>
                        <li>Midtkraft</li>
                    </ul>
                </div>
            </section>                
            <section>
         ${this.articles.map(
            article =>
                html`
                <div>
                    <sdk-article data=${article}></sdk-article>
                </div>
            `,
        )}
            </section>
        </section>
`;
    }
}

customElements.define('praksis-view', PraksisView);

In the above code, I am loading some test data from testData.json.

Now, let's take a look at another element called sdk-article:

import {LitElement, html} from '@polymer/lit-element';


class SdkArticle extends LitElement {
    static get properties() {
        return {
            data: {type: Object}
        };
    }

    constructor() {
        super();
        this.data = {};
    }

    render() {
        this.generateHtml();
        return html`
    `;
    }

    generateHtml(){
        console.log(this.data);
    }
}

customElements.define('sdk-article', SdkArticle);

This element simply checks if the data is present.

However, when I run the code, the data appears to be undefined, and an error is thrown:

VM1588:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1
    at JSON.parse (<anonymous>)
    at fromAttribute (updating-element.js:59)
    at Function._propertyValueFromAttribute (updating-element.js:259)
    at HTMLElement._attributeToProperty (updating-element.js:387)
    at HTMLElement.attributeChangedCallback (updating-element.js:343)
    at AttributeCommitter.commit (parts.js:79)
    at AttributePart.commit (parts.js:111)
    at TemplateInstance.update (template-instance.js:40)
    at NodePart.__commitTemplateResult (parts.js:248)
    at NodePart.commit (parts.js:189)

If anyone can spot the issue here, I would greatly appreciate the help.

Answer №1

Solution

If you want to transfer the actual property, you should use the "dot notation".

<sdk-article .data=${article}></sdk-article>

This is essentially equivalent to

document.querySelector('sdk-article').data = article;

Explanation of the Problem

The issue in your existing code lies in setting an attribute.

<sdk-article data=${article}></sdk-article>

It is basically interpreted as

document.querySelector('sdk-article').setAttribute('data', article);

However, attributes can only accept strings.

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

arrange data based on table heading using vue.js

I've recently upgraded to Vue 2.x and found out that the orderby directive is no longer supported as per this documentation. I'm trying to avoid adding another JavaScript library, but if using lodash is the only option, I'm willing to give ...

Optimal timing for fulfilling promises in AJAX requests

Recently, I've delved into the world of promises to handle multiple ajax calls without knowing in advance how many will be required. In my journey, I came across these valuable posts: jQuery Deferred - waiting for multiple AJAX requests to finish jQu ...

The Three JS on the website is error-free, yet it fails to function properly

I've been attempting to replicate the example three.js page on my own website, complete with a canvas for the 3D animation. However, I'm encountering an issue where nothing is displayed, despite no errors appearing. I've tried troubleshootin ...

Aligning dynamically-sized TextInput in React Native

I am facing a challenge in centering a text input with a width that matches the length of the input text. I have tried using alignSelf: 'center' and alignItems: 'center', but the text input is not visible without specifying a width. Fo ...

Adjust Javascript to modify the URL by assigning a new URL without utilizing the origin as the parent

Currently, I am working on a script that is responsible for sending string values to the server in order to change the ipv4 information on a specific device. However, I am facing some difficulties and would appreciate some assistance with automatically upd ...

Encountering an issue with Angular build in Docker: [ERR_STREAM_DESTROYED] - Write function cannot be called after a stream

Below is the docker file I'm using to build my Angular project: FROM node:12-buster-slim as build-step RUN mkdir -p /app COPY . /app WORKDIR /app RUN chmod 777 -R /app RUN npm install ARG configuration=production RUN npm run build -- --output-path=./ ...

What is the best way to include an icon before each option in a VuetifyJS combobox?

I'm looking to enhance the combobox feature in VuetifyJS by adding an icon before each option in the dropdown menu. Can someone guide me on how to achieve this functionality? You can check out a sample of the combobox on CodePen here: https://codepen. ...

Why isn't my React JS react-router Link directing me to the intended page?

I am encountering an issue with my routing setup in App.js. I have defined the routes as shown below: function App() { return ( <BrowserRouter> <div className='App'> <Switch> <Route exact path="/"><Inde ...

Using a Javascript method to access a sibling property within an object

Is there a way to access a sibling property from a method in JavaScript? This seemingly simple task has proven challenging for me. Take a look at the sample code below. let f = { a: 3, printMyBrother() { console.log(X) } }.printMyBrother f() ...

I'm having trouble getting my JQuery function to activate

I'm struggling to make my background image follow the movement of my mouse as it hovers over the objects with the #titleheader class. The page is displaying correctly, but the interactive functionality isn't working. I am developing in Django. I ...

Exploring the quirky characters in the PHP mail() function

Currently using the php mail function, it's somewhat effective, although not my preferred method. However, it seems I must make do for now. The issue at hand is that special European characters are showing up strangely in the email. I attempted to se ...

Utilize JavaScript code from an npm package to incorporate its functionality within your program

I have recently integrated the htmlhint library into my development workflow. I am able to execute it via the command line on any HTML file using the following command: npx htmlhint src/test-file.html Upon running this command, the file is linted and any ...

Tips on how to ensure that an onClick JS function only runs when radio buttons are selected

I have implemented the formslider library for a form on my website. In the demo, the slide transitions to the next set of questions based on a click event triggered by radio buttons (answers). However, when I attempted to include checkboxes for users to s ...

The data for my registration is not getting stored in the Firebase database as expected

I'm currently working on a registration app and it's my first time using firebase. My email address is successfully stored in the authentication section of firebase. However, when I try to connect my app to the database to store additional infor ...

JavaScript oddity with closure problems

Why did I receive ['undefined1','undefined2'] as the value for my array in this specific case, even though I pushed it in the same scope? router.post('/add', function(req, res) { var imageArr = []; for(var i = 1; i &l ...

What are the signs that a promise has been kept, allowing me to chain onto it or extract its outcome?

After a user selects an employee, I trigger an asynchronous request to the server in order to retrieve the employee's events. In case the user tries to assign a task to the selected employee before receiving the event list from the server, I must post ...

I am having trouble getting the minimum value as it keeps displaying 0. However, when using Math.max(), it correctly displays the maximum value. Can anyone explain why this is the case?

Why am I not getting the minimum value when it displays 0, but Math.max() correctly shows the maximum value? function findMin(ar) { var min_val = 0; for(var i = 0; i < ar.length; i++) { min_val = Math.min(min_val,ar[i]); } document.write(m ...

The error message "TypeError: firebase.firestore() is not a function in web JavaScript" indicates

Currently, I am encountering an issue while attempting to upload an image on Firebase Cloud Storage using web Javascript. The error message "firebase.firestore() is not a function" is being displayed in my console. Do you think I might be going about this ...

"How can I open a DOCX file in a new window using JavaScript and then close the window

When attempting to open a doc/docx file in Word from an HTML link, my goal is to prevent the opening of a new browser window. First attempt: mywin=window.open("filename.docx","viewer"); The first attempt works fine, but it results in opening a new "view ...

Changing text color based on positive or negative value in JavaScript(React)

Greetings everyone! I'm currently working on a specific feature that requires the color of a value to change dynamically. If the value is above 0, it should be displayed in green; if below 0, in red; and if equal to 0, in orange or yellow. To achieve ...