The reference was altered prior to updating the reference

I am attempting to replace an object's property (a string) with a matching keyed object from another object where the values are also keyed.

For example...

const dataRefs = {
  'idkey1': { title: "Key1", /*...etc... */ },
  'idkey2': { title: "Key2", /*...etc... */ },
  'idkey3': { title: "Key3", /*...etc... */ },
  // ...etc...
};

const pages = [
 { title: "A Page", data: 'idkey1' },
 // ...etc...
];

With the code below, my goal is to substitute pages[n].data with the corresponding property in dataRefs. When looping through the pages using forEach...

pages.forEach(page => page.data = dataRefs[page.data])

However, after doing this, the page.data property turns out to be undefined, despite it should match.

When trying to debug by console output, I observe an odd behavior where the undefined value only appears when the code is added after the output...

// This works perfectly and achieves the desired match.
pages.forEach(page => console.log("%s: ", page.data, dataRefs[page.data]));
// Output:
//  idkey1: undefined

// On the other hand, this leads to unexpected results and ends up with "undefined".
pages.forEach(page => {
  // using console.log to see what's going on...
  console.log("%s: ", page.data, dataRefs[page.data]);
  page.data = dataRefs[page.data];
});
// Output:
//  [Object object]: undefined

// Trying this alternative, just in case how the DOM inspector 
// might be using references, but still the same issue...
pages.forEach(page => {
  console.log(page.data + ": ", dataRefs[page.data]);
  page.data = dataRefs[page.data];
});
// Output:
//  [Object object]: undefined

I have double-checked variable spellings and tried various permutations of the code repeatedly, but it seems that no matter what I attempt, calling page.data = dataRefs[page.data] does not function as expected. Could this be a complex race-condition or maybe I've been watching too much Matrix lately?

This is being executed within the Component's render() method.

Using Safari 14.1.2 for reference.

Answer №1

An unexpected issue arose in relation to Next.JS, where it seemed that pre-rendered data was being manipulated before reaching the component render function. This was evident when setting a breakpoint at a specific line of code and observing that the data had already been altered prior to the expected point of manipulation.

Upon further investigation, it appeared that this could be attributed to some aspect of NextJS's pre-lifecycle processes, potentially linked to the SSG process.

To address this peculiar behavior, a workaround involving a check to prevent double execution was implemented. Although not ideal, it effectively resolved the issue for the time being. The modified code snippet now includes an additional conditional statement within the loop to handle the data conversion only once.

pages.forEach(page => {
   // Skip if data has already been converted
   if (page.data instanceof Object) return;

   // Convert data if still a string reference
   page.data = dataRefs[page.data]));
});

This solution may not provide the most optimal answer, but given the unusual nature of the problem and considering previous experiences with Javascript, it appears to be a specific quirk related to NextJS/SSG or another underlying processor. Any insights from experienced NextJS developers would be greatly appreciated.

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

The issue of uploading files using Ajax in CodeIgniter and Jquery is causing problems

I am attempting to implement a file upload using Ajax in CodeIgniter, but it seems like my Jquery code is not properly retrieving the data from the form even though the file appears to be included in the POST message. Below is my controller: public funct ...

Ways to examine a JavaScript Bound Function

Can a JavaScript bound function be inspected somehow? I need to be able to return a bound function from a function, and when unit testing, I'd like to verify the bound function's target, boundThis, and boundArgs. These properties seem to be inte ...

Why is getAuth().onAuthStateChanged not triggering in capacitor even though async function is not resolving?

I have encountered a possible issue related to Firebase or promises in Capacitor while developing an iOS app with Capacitor and NextJS. I have noticed that async functions, especially those related to Firebase, do not complete even after successful execut ...

The angular controller function is failing to set $scope.value

I've been facing an issue with setting an Angular variable value in a controller function that is created by a directive. For some reason, it doesn't seem to work when I try to assign the value within the controller function, even though it displ ...

State dropdown in Angular dynamically updates based on the country selected

I am in search of a contextual state dropdown menu that is linked to the country, ensuring only relevant states are displayed. I have explored these two solutions for guidance in my project. Angularjs trigger country state dependency angularjs dependant ...

Searching for a specific collection item based on a custom property (excluding _id) in Meteor - what's the best approach?

I am facing an issue with my application that utilizes Flow Router along with its pub/sub functionality. I have set up a collection and template helpers. The code works fine on the client side. Template.theCase.helpers({ theCase: function () { ...

Reboot JavaScript once a day for optimal performance

Is it possible for the JavaScript's ?random to be based on the current date so that it only loads once a day? <script type="text/javascript" src="http://external.example.com/bookmarklet.js?random"></script> I am asking this question beca ...

Tips for transferring the text from a textbox to a href reference

I am currently working on a webpage that includes a text box, a button, and an a element. I want to input a website URL into the text box and pass it to the a element. Here is what my code looks like so far: <a id="weburl" href="http://jquery.com/"&g ...

Error: An unexpected 'if' token was not caught

Encountering an error related to the question title while working with this code snippet: $LAB.queue(function setup() { FB.init({ appId: '00000000', status: true, cookie: true, xfbml: true, logging: &ap ...

Tips on automating the process of moving overflowing elements into a dropdown menu

Challenge Description In need of a dynamic navigation bar, I faced the problem of displaying only the first X items on one line and have the remaining items hidden in a "Show more" dropdown. The challenge was to calculate the width of each item accurately ...

Colorful Paper Trail Logging

After stumbling upon a post on the internet, I discovered that Papertrail offers the ability to log using ANSI colors. This is particularly appealing to me as my node.js app generates numerous logs, and adding color helps me decipher the information during ...

How can you send an array from Django to JavaScript without using u''?

When viewing the data: 'some_array': ['text1','text2', 'text3'] Upon trying to pass it to a JS script in the template: <script type="text/javascript"> some_func({{ some_array }}); </script> Howeve ...

Differences between Mongoose's updateOne and save functions

When it comes to updating document records in a MongoDB database, there are several approaches to consider. One method involves defining the User model and then locating the specific user before making modifications and saving using the save() method: let ...

V-Calendar is not displaying the accurate dates

https://i.stack.imgur.com/zk4h7.png The image displays dates starting on June 1, 2022, which should be a Wednesday but appears as a Sunday on the calendar. This issue affects all months as they start on a Sunday instead of their respective weekdays. The p ...

Checking for Files without Compiling: A guide to using Webpack 2

I have a scenario where I am importing several .css files from npm modules in my main.js file, which serves as the entry point for my webpack configuration. Here is an example of how it's set up: "use strict"; const ExtractTextPlugin = require("extra ...

Clearing the Value of a Linked Ant Design Cascading Dropdown Select in Next.js/React.js

I'm currently developing a React form with the assistance of Ant Design's Form component. The form boasts various dropdowns such as facility, specialization, and doctor. It is imperative that when the values in the facility or specialization drop ...

Using AngularJS to access JSON files through the $http service

I'm experiencing difficulties reading data from my test.json file using the #http service. I have everything set up on a xampp localhost, but I can't seem to figure out what's going wrong. Here's the JavaScript code. Thank you in advanc ...

Is there a way to prevent jQuery.ajax() from displaying errors in the console?

I have set up a jQuery JSONP request to monitor the status of a resource based on its URL. In case the resource is not accessible or the server goes down, my ajaxFail() function takes care of updating the display. function fetchServerStatus(service, host) ...

Issue encountered: Django Rest Framework functionality fails to execute properly when accessed from varying URLs

I'm currently immersed in the tutorial found at: http://www.django-rest-framework.org/ as I endeavor to construct a restful API for my django application, which is being hosted on apache. My ultimate goal is to utilize ajax in order to call the API an ...

Encountering a 'Object is not a function' issue while attempting to implement Page Object with Protractor

Whenever I attempt to run my tests, I keep encountering a TypeError: object is not a function. Prior to incorporating PageObject, everything worked fine. Below is my spec.js 'use strict'; var todoAppPage = require('../pages/angular.page&a ...