Incorporating props into every page through getInitialProps in Next.js

I am trying to ensure that the same props are loaded on all pages I navigate to. My approach involves using _app.js as shown below:

export default function MyApp({ Component, pageProps }) {
    return <Component {...pageProps} />
}
    
MyApp.getInitialProps = async (appContext) => {
    return {
        props: {
            testApp: ['1', '2', '3'],
            testApp2: '222'
        }
    }
}

However, this method is not yielding the expected results as I am receiving an empty object:

const Error = (props) => {
    console.log(props);

    return (
        <div className="error-page">
            ...
        </div>
    )
}

What mistake have I made in my approach?

Answer №1

When using the getInitialProps method, the structure of the return object differs from that of getServerSideProps and getStaticProps. In getInitialProps, you don't need to nest the props within an extra props object; instead, you simply return the object with the props directly.

MyApp.getInitialProps = async (appContext) => {
    return {
        testApp: ['1', '2', '3'],
        testApp2: '222'
    }
}

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

Performance of Bloom Effect in Three.js

The frame rate ranges from 50 to 60fps without the bloom effect being applied. renderer.render( scene, camera ); However, once the bloom effect is added, the frame rate drops significantly to just 10fps. camera.layers.set( BLOOM_SCENE ); bloomComposer.r ...

What is the method for obtaining a date in the format of 2018-05-23T23:00:00.000+00:00?

Recently, I've been attempting to filter data based on dates in my database. The format in which the dates are saved is as follows: 2018-05-23T23:00:00.000+00:00 This was my initial approach: router.get('/byDate', function (req, res) { ...

What is the best way to send data from a React.js application to AWS Lambda?

I'm having trouble sending data from my React application to an AWS Lambda function through API Gateway. Here is the code snippet from my React app: const exampleObj = { firstName: 'Test', lastName: 'Person' }; fetch(process.env.R ...

Would you like to learn how to dynamically alter a button's color upon clicking it and revert it back to its original color upon clicking it again?

My Upvote button starts off transparent, but when I click on it, the background color changes to green. What I need is for the button to become transparent again when clicked a second time. I've attempted using the following code snippet: function ...

Encountered an Angular 1.6 Error: The requested URL at http://127.0.0.1:56035/[url] could not be found (404

I've hit a roadblock in my project and can't seem to figure out the issue. The file I'm working on is supposed to display an iframe video player with a YouTube embed. I tried using interpolation to construct the correct URL: <div class= ...

Error encountered: attempting to build for the iOS Simulator, although linking a dylib compilation specifically for iOS, such as the file 'TitaniumKit.framework/TitaniumKit' for the arm64 architecture

Whenever I attempt to build my appcelerator app for ios, I encounter this error: ld: building for iOS Simulator, but linking in dylib built for iOS, file 'Frameworks/TitaniumKit.framework/TitaniumKit' for architecture arm64 Despite my efforts to ...

How to access specific values from a deserialized JSON string using Javascript

Within the nested for loops, I have the following row: document.getElementById("sm" + i + "b" + j).innerHTML = jsonval.values.sm1b1; ^^^^^^ In order to change the va ...

Is it possible to create an index.html page with all the necessary head tags to prevent duplicate code across multiple html pages?

Imagine I am using app.js or a Bootstrap CDN link for all of my HTML pages, but I don't want to include it in every single page individually. Is there a way to create an index.html file that includes this so that all other HTML pages load the head fro ...

The Chocolat.js Lightbox plugin is experiencing issues with jQuery as it is unable to detect the

I am in the process of integrating chocolat.js into a basic website. An issue I encountered was that the thumbnail was directly processing the anchor link, which resulted in the image opening in a new window instead of launching it in a modal on the screen ...

Unable to utilize navigator.camera.getPicture in iOS while using PhoneGap Adobe Build

I've spent hours searching, trying to troubleshoot my PhoneGap app (compiled by Adobe PhoneGap Build) and I suspect there's something crucial about PhoneGap that I'm missing. I've added the following lines to the config.xml file: <f ...

What causes the issue of JavaScript code not loading when injected into a Bootstrap 4 Modal?

I've created a JavaScript function that triggers the opening of a Bootstrap Modal Dialog: function displayModal(message, headerMessage, sticky, noFooter){ var modal = $('<div />', { class: 'modal fade hide ...

Unlocking the Power of Session Variables in AngularJS using Ui-router

Currently, I am utilizing Angular to manage routes. On the server side, Passport is being used so that I can access the user session variable req.user in my views. However, when dealing with a route rendered by ui-router, my req.user ends up being undefine ...

Increase in JQuery .ajax timeout not effective

My website has a process where JavaScript sends a POST request to a PHP server using the .ajax() function. The PHP server then communicates with a third-party API to perform text analysis tasks. After submitting the job, the PHP server waits for a minute b ...

Why is it difficult to display data fetched through getJSON?

The test-json.php script retrieves data from the database and converts it into JSON format. <?php $conn = new mysqli("localhost", "root", "xxxx", "guestbook"); $result=$conn->query("select * From lyb limit 2"); echo '['; $i=0; while($row ...

Error: The function $(...).maxlength is not recognized - error in the maxlength plugin counter

I have been attempting to implement the JQuery maxlength() function in a <textarea>, but I keep encountering an error in the firefox console. This is the code snippet: <script type="text/JavaScript"> $(function () { // some jquery ...

Retrieve PDF files from mongoDB and render them in an HTML format

After successfully uploading a PDF to mongoDB, I encountered an issue with reading and displaying it. To read the uploaded PDF, I converted it using the following code: var buf2 = new Buffer(data).toString('base64'); The resulting format of th ...

Math operations limited by boundaries: adding and subtracting

What is the proper way to implement this logic in JavaScript: Row-=21; if (Row < 1) { Row = 1; } ...

Text that is selected within a contenteditable div: Find the beginning and end points of the highlighted text

<div contenteditable="true">This text is <b>Bold</b> not <i>Italic</i> right?</div> For instance, if the text appears in a bold format, but not italic and the user selects it, how can I determine the exact position ...

I want to establish the identical response output field name in NestJS by utilizing the @Expose decorator from class-transformer

My Entity definition currently looks like this: export class ItemEntity implements Item { @PrimaryColumn() @IsIn(['product', 'productVariant', 'category']) @IsNotEmpty() itemType: string; @PrimaryColumn() @IsU ...

Troubleshooting MaterialUI Datatable in Reactjs: How to Fix the Refresh Issue

Currently, I am facing an issue with rendering a DataTable component. The problem is that when I click on the "Users" button, it should display a table of Users, and when I click on the "Devices" button, it should show a table of Devices. But inexplicably, ...