5

I'm new to NextJS, and trying to figure out, how to create a global variable that I could assign a different value anytime. Could someone give a simple example? (I know global might not be the best approach, but still I would like to know how to set up a global variable).

Let's say:

_app.js

NAME = "Ana" // GLOBAL VARIABLE

page_A.js

console.log(NAME) // "Ana"
NAME = "Ben"

page_B.js

console.log(NAME) // "Ben"
Isaac Michaan
  • 353
  • 1
  • 2
  • 11
  • 1
    Does this answer your question? [How to declare a global variable in React?](https://stackoverflow.com/questions/34351804/how-to-declare-a-global-variable-in-react) – juliomalves Feb 13 '22 at 17:06
  • 2
    No, but this does: https://www.netlify.com/blog/2020/12/01/using-react-context-for-state-management-in-next.js/ and this does: https://reacttricks.com/sharing-global-data-in-next-with-custom-app-and-usecontext-hook/ and also this: https://www.linkedin.com/pulse/react-context-api-nextjs-axel-laurent-obscura-sarzotti thanks anyways – Isaac Michaan Feb 13 '22 at 19:12

4 Answers4

5

try using Environment Variables

/next.config.js

module.exports = {
  env: {
    customKey: 'my-value',
  },
}

/pages/page_A.js

function Page() {
  return <h1>The value of customKey is: {process.env.customKey}</h1>
}

export default Page

but you can not change its contents, except by changing it directly in next.config.js

Pausi
  • 134
  • 2
  • 7
0

Nextjs no special ways to provide global variables you want. You can achieve by:

  1. Stateful management tool, like redux-react
  2. Using Context
Pandy
  • 138
  • 1
  • 4
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 20 '22 at 11:49
0

It's not like it's impossible, I created a file called _customGlobals.jsx and put this as content

String.prototype.title = function () {
  const sliced = this.slice(1);
  return (
    this.charAt(0).toUpperCase() +
    (sliced.toUpperCase() === sliced ? sliced.toLowerCase() : sliced)
  );
};

and imported it in _app.jsx like this:

import "./_customGlobals";

So now I can call this function on any string anywhere in my project like this: "this is a title".title()

yashas123
  • 270
  • 5
  • 23
0

Database designed for this purpose. But for one var it's not wise to install whole db! So, you can do it in a JSON file.

Add a var to a JSON file and use a function to update it. this is a simple function for this usage:

const fs = require('fs');

function updateJSONFile(filePath, updates) {
  fs.readFile(filePath, 'utf8', function (err, data) {
    if (err) {
      console.error(err);
      return;
    }

    let json = JSON.parse(data);

    for (let key in updates) {
      json[key] = updates[key];
    }

    fs.writeFile(filePath, JSON.stringify(json, null, 2), 'utf8', function (err) {
      if (err) {
        console.error(err);
      }
    });
  });
}

So, use it like this:

updateJSONFile('file.json', { name: 'John Doe', age: 30 });

You can create another function to read it dynamicly:

function readJSONFile(filePath) {
  fs.readFile(filePath, 'utf8', function (err, data) {
    if (err) {
      return callback(err);
    }

    let json;
    try {
      json = JSON.parse(data);
    } catch (error) {
      return callback(error);
    }

    return callback(null, json);
  });
}

and you can use it like this:

const readedFile = readJSONFile('file.json')

I deleted the callback function to have a simple code but you can add callback function to log error messages.

Radmehr
  • 299
  • 2
  • 12