Search code examples
javascriptjquerygetaxiosmomentjs

Data on page is different than data in console


I'm performing a GET request to show information on a page---in my console I can see that the dates for _data.Created are correct, but on the page itself it's showing today's date of December 2nd. I'm using moment.js to format the Created date.

The most recent change I made was getting rid of a <p> tag that used to be in between the <a> tags, but I can't see how that would've messed with the dates. Also, I can't recall seeing this error in the past, but it's possible that I missed it.

Any ideas as to what's going on and how I can fix it? It would be much appreciated.

JS:

async function displayAnnouncements() {
    axios.get(`${_something}/_api/lists/GetByTitle('someName')/Items?$select=ID,Title,Body,Created,Link&$orderby=Created%20desc&$top=4`, restHeaders)
         .then(resp => {

            let _data = resp.data.d.results;
            let _newDate = moment(_data.Created).utc().format("MMMM D, YYYY");

            console.log(_data)

                _data.slice(0, 4).forEach(m => {
                    const itemLink = $(`<a href="#close" data-toggle="modal" data-target="#bkEvts-${m.ID}" class="cont_evts-link" title="View Announcement">
                        <b>${m.Title}</b> - <i>${_newDate}</i>
                    </a><br>`)

// etc

Here's the console and the page:

enter image description here


Solution

  • _data is an array. _data.Created will result in undefined. So you're passing undefined to moment which will fall back to today.

    Instead format the date for each item in the array.

    async function displayAnnouncements() {
        const resp = await axios.get(`${_something}/_api/lists/GetByTitle('someName')/Items?$select=ID,Title,Body,Created,Link&$orderby=Created%20desc&$top=4`, restHeaders)
        let _data = resp.data.d.results;
        _data.slice(0, 4).forEach(m => {
            let _newDate = moment(m.Created).utc().format("MMMM D, YYYY");
            const itemLink = $(
                `<a href="#close" data-toggle="modal" data-target="#bkEvts-${m.ID}" class="cont_evts-link" title="View Announcement">
                    <b>${m.Title}</b> - <i>${_newDate}</i>
                </a><br>`
            );
        });
    };