Error Trying to use JSON Objects with JavaScript ES6 Template Literals

118 views Asked by At

I am trying to use template literals for the first time but I am running into an error that I can't debug after reading a few other resources.

$.ajax({
    // usual things
    success: function(data) {
        // add a manual note before looping through the ones returned via ajax
        var nowNote = { status: `now`, text: `Now`, created_at: null };
        var notes = data.notes;

        var timeline =  `

            ${noteTemplate({ nowNote })}

        `;
        // take out ${timelineTemplate({ notes })} for now
    }
});

var timelineTemplate = ({ notes }) => {
    return `
        ${notes.map(note => noteTemplate({
            note
        })).join('')}
    `;
}

var noteTemplate = ({ note }) => {
    return `

       ${note.created_at == null ?
           ''
       : `<strong>${moment(note.created_at).format('DD/MM/YYYY HH:mm')}</strong>`}

       <span>${note.text.replace(/(?:\r\n|\r|\n)/g, '<br>')}</span>
    `;
}

The error message on the console is:

Uncaught TypeError: Cannot read property created_at of undefined when trying to do the comparison of note.created_at with null.

It doesn't seem to like using dot notation for accessing the properties which makes me think I've done something fundamentally wrong that I'm too ignorant of to debug at the moment.

Basically I'd just like to pass a json object to the template literal and build a component from it using it's properties whilst also being able to use conditionals etc.

1

There are 1 answers

1
Pablo Lozano On BEST ANSWER

Your problem is you are declaring your function as :

var noteTemplate = ({ note }) => {
    return `

       ${note.created_at == null ?
           ''
       : `<strong>${moment(note.created_at).format('DD/MM/YYYY HH:mm')}</strong>`}

       <span>${note.text.replace(/(?:\r\n|\r|\n)/g, '<br>')}</span>
    `;
}

So it is specting an object which has an attribute named note.

You can remove the curly braces in the declaration or pass as parameter something like {note: nowNote} instead of just note