Im trying to simply have a shared variable between my pages in my Next.Js application.. My _app.js below contains the following..
import { useState } from 'react';
const CustomApp = ({ Component, pageProps }) => {
// Variables
const [testVariable, setTestVariable] = useState(0)
// globalFunctions
const setTestVariable = (newValue) => setLocalVariable(newValue);
return (
<Component
{...pageProps}
// Export Variables
testVariable={testVariable}
// Export Functions
setTestVariable={setTestVariable}
/>
);
}
export default CustomApp
I have two pages... Both are the same except one is called index.js and exports Home, the other is called about.js and exports About...
import { useState, useEffect } from 'react'
import 'bulma/css/bulma.css'
import styles from '../styles/Home.module.css'
const Home = ({ testVariable, setTestVariable, }) => {
useEffect(() => {
})
return (
<div id={styles.outerDiv}>
<Head>
<title>My Next.Js Page</title>
<meta name="description" content="A Next.js application" />
</Head>
<div id={styles.navBar}>
<a href="/" id={styles.navLink}>
<h3>Home</h3>
</a>
<a href="/about.js" id={styles.navLink}>
<h3>About</h3>
</a>
</div>
<div id={styles.content} className="content">
<br/>
<h2>Test Variable: {testVariable}</h2>
<button id={styles.incrementButton} onClick={setTestVariable(1)}>Set Test Variable to 1</button>
</div>
</div>
)
}
export default Home
When I tap the button the variable on my page changes to 1, however when I switch pages the variable goes back to 0. I also receive no errors of any sort. All feedback is greatly appreciated! Thanks for your time.
CodePudding user response:
The variable goes back to 0 because you are using a
tags wich "reloads" the page
To navigate you should use the Link
component that is built in next.
This Link
component prevents the default behavior of reload the page and you can keep your state while navigate on the page