The project runs smoothly on my local host, but encounters an issue during the build process

I am currently working on a Preact-CLI project that utilizes Preact-Router. Everything functions as expected when testing on localhost, but once the project is built and deployed to production, issues arise.

One particular page within the project pulls content dynamically from a JSON file (located internally). To achieve this, I have duplicated the same page object to accommodate different content for each page.

The problem arises when attempting to match the page URL (retrieved using this.props.permalink) with the corresponding title in the JSONObject. While this process works flawlessly on localhost, inconsistencies surface in the production environment.

Issue: All pages seem to be displaying the content of the first JSON element instead of their respective content. Initially, it was suspected to be a server-related problem, but further investigation revealed discrepancies in the builded files post-prerendering/build process. Consequently, the prerendered HTML of one page mistakenly contains the content intended for another.

My assumption is that during the build process, this.props.permalink fails to function properly. How should I address this issue?

Additional information: I employ the prerender function without utilizing the service worker feature for the build.

Appreciate any assistance!

UPDATE: Following some modifications to the function, I intuitively realized the necessity of setting dynamic content via a loop. This allows the compiler to iterate through it during the build process, ensuring all pages are correctly prerendered.

Although the iteration and state setting are successful, only the final element of the PrerenderUrls array ends up being stored. Consequently, all pages end up displaying the JSON content belonging to the first element.

componentWillMount() {
        for (var i = 0; i <= PrerenderUrls.length; i++) {
            // code snippet
            let removeDash = new RegExp("-")
            var needle = PrerenderUrls[i].title
            var needle1 = needle.replace(removeDash, " ")
            alert("1")

            if (needle1 != "Homepage") {
                for (var x = 0; x < Data.length; x++) {
                    let removeDash = new RegExp("-")
                    var nodash = Data[x].title.replace(removeDash, " ")
                    var nocaps = nodash.toLowerCase()
                    if (nocaps == needle1) {
                        alert("needle2: "+ needle1 + " nocaps: " + nocaps)
                        this.setState({
                            pageTitle: Data[x].title,
                            descShort: Data[x].descShort,
                            description: Data[x].desc,
                            img: Data[x].img
                        })
                        alert("state "+ this.state.pageTitle)
                    } 
                } 
            }
        }

Answer №1

Based on the details you've shared, it appears that you're encountering a traditional Javascript closure challenge. I see that you're utilizing both let and var. If your environment supports let, opt for it over var. This switch will likely resolve your closure issues since let establishes variables within block scope rather than function scope. Alternatively, if let isn't an option, consider mimicking its functionality manually by passing the variable to the callback function, like so:


    // ...
    for (var x = 0; x < Data.length; x++) {
        try { throw x }
        catch(iterator) {
            this.setState({
                pageTitle: Data[iterator].title
            });
        }
    }

PS. It can be challenging to decipher your code when it's tailored so specifically to your application. Simplifying and honing in on the main issue could greatly aid in troubleshooting. A lot of the provided code seems extraneous and may not directly relate to the problem at hand.

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

Containers shared among Next.js pages within a folder

Is it possible to have a shared container for all pages within a specific folder in NextJS? One potential solution could involve the following code: // pages/folder/index.js export default function Container({ children }) { return <Container>{ch ...

Issue with updating required Node.js/Express modules using Chokidar?

After browsing through numerous questions and answers regarding chokidar, I am still struggling with an issue. It would be greatly appreciated if someone could help debug my particular code snippet. The Express node app I am working on is running at local ...

Combining DataFrames in PySpark by appending a constant value column from one DataFrame to another

My scenario involves working with two Spark dataframes: >df1 +---------------+ | values| +---------------+ |[a, b, c, d, ..| +---------------+ >df2 +---+---------+ | id| number| +---+---------+ | 1| 34523| | 2| 56438| | 5| 9034 ...

Transferring the state from a parent component to a child function

I'm having trouble passing a state from a component to a function. I was able to pass the state from Home to ListHome, but I'm struggling to continue passing it to a function within ListHome (Slider) because it's a function. Even after revi ...

Angular JS - the culprit behind app crashes in Safari and IE

I'm encountering an issue with my Angular JS app. There is some code that counts the characters from an array, but for some reason it is causing the app to break and stop working in Safari and IE. I've tried to figure out what's wrong, but c ...

The idea of a webpage completely powered by Ajax

I'm currently in the process of creating a compact website that utilizes full ajax requests for features such as login and registration, all done asynchronously. However, I've come across an issue where if a user decides to refresh the site, any ...

Tips on adjusting the pixel dimensions of an image using a file object

Within a form on our website, users have the ability to upload an image file. To ensure quality control, I've set up validation to confirm that the uploaded file is either an image or gif format. In addition to this, I'm looking for a solution th ...

Vue.js global event issue

Recently, I encountered an issue with the following code: <component-one></component-one> <component-two></component-two> <component-three></component-three> Specifically, component-two contains component-three. My cu ...

Vue router is unable to verify the user's authentication

I have certain app routes that are supposed to be restricted to admins only. I've added requiresAdmin: true, to the meta of those routes, but for some reason it doesn't prevent other users from accessing them. Code Note: I've included comme ...

Deploying a React App to Github Pages Results in a Blank Screen

After successfully uploading a simple react app onto GitHub pages using gh-pages, I attempted to import the Shards dashboard project (https://github.com/DesignRevision/shards-dashboard-react) onto my GitHub page. Unfortunately, all I see is a blank page. ...

Unable to see Bootstrap 5.2 Modals in action with documentation demo

Here is an example that I copied and pasted from the documentation on https://getbootstrap.com/docs/5.2/components/modal/: <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-bs-toggle="modal&q ...

Utilize React.js ThemeProvider to dynamically change themes based on routing

Hey everyone, I have a question regarding changing the theme provider based on the route in my code snippet: const rootElement = document.getElementById('root'); ReactDOM.render( <ThemeProvider theme="MyThemes.default& ...

Retrieve the value of the object within the mysterious index loop in JavaScript

I have retrieved search results from the data, and each time the index of my search result varies. At one point, the result may appear in the 4th index, while at another time it might be in the 100th index. How can I retrieve the rank value from within t ...

Tips on avoiding the conversion of the ✳ symbol into an emoji

My issue lies in my ✳ (Eight-Spoked Asterisk) symbol being converted to an emoji on iOS/android devices. Find more about the Eight-Spoked Asterisk Emoji here. Could someone guide me on how to prevent the normal symbol ✳ from being transformed into an ...

I'm looking for a method to retrieve the value of an option tag and then pass it to a helper within handlebars. Can someone

Currently, I am utilizing express and handlebars in my project. I have a specific view where I aim to display certain information based on the event when a client selects an option from a select tag. However, I have some queries regarding this: Is it fea ...

When integrating React with Tawk, the user's name and email are automatically encoded before being sent

My code within the componentDidMount() function initializes a widget popup when the page loads. It then sets the name and email using parameters received from the previous page. const fullName = this.state.data[0]; console.log(fullName); const e ...

Utilizing F# for multidimensional array comprehension

Is there a specific syntax in F# for creating multidimensional arrays using comprehensions? While it's simple for jagged arrays like this: let weights1 = [| [|3.0|] [|1.0|] |] It's possible to ...

Is it possible to trigger the execution of two functions simultaneously by using onClick in JavaScript?

I currently possess: one = () => { //perform a task } two = () => { //execute an action } <div> <button onClick={/*this.one, this.two (it doesn't function)*/}>Go</button> </div> Is there a way to invoke two f ...

Set the error state of a TextField in Material UI to true based on the user's input

Being a newcomer to React and Javascript, I have made some progress but now find myself stuck. I am struggling with how to change the error state of a Material UI TextField based on user input. Specifically, I want the error to be triggered if the user inp ...

Retrieve the appended element's object

I am currently facing an issue with accessing elements that are automatically added by a library in my code. In my HTML, I have the following line: <div class="bonds" id="original" style="display:block;"></div> The library appends some elemen ...