Search code examples
reactjsnext.jsreact-context

React Context not updating value to pass to another page


I am creating an ecommerce app with Nextjs and want to share data between pages. I know that we can't use props to pass data between the pages and so was looking into react context api. This is my first time using react context api. I've researched and found that you should add the Provider in the _app.js page in nextjs. But this shares the data among all the pages. Plus my data is being retrieved by getStaticProps in the slug page of the app. I want to get this data into the checkout page of my app.

This is the context I have created:

import { createContext, useState, useContext } from 'react';

const productContext = createContext({} as any);

export const ProductProvider = ({ children }) => {
  const [productData, setProductData] = useState('');
  return <productontext.Provider value={{ productData, setProductData }}>{children}</productContext.Provider>;
};

export const useProduct = () => useContext(productContext);

_app.js

import { ReportProvider } from '../contexts/ReportContext';
export default function CustomApp({ Component, pageProps }) {
  return (
  
            <ReportProvider>
              <Component {...pageProps} />
            </ReportProvider>
          
  );
}

I import this into the slug page and try to update the state from here

// [slug].js

import client from '../../client'
import {useProduct} from './productContext';

const Post = (props) => {
  const {setProductData} = useProduct();
  const { title = 'Missing title', name = 'Missing name' , price} = props
  setProductData(title);
  return (
    <article>
      <h1>{title}</h1>
      <span>By {name}</span>
      <button>
           <a href="/checkout">Buy Now</a>
     </button>
    </article>
  )
}

Post.getInitialProps = async function(context) {
  const { slug = "" } = context.query
  return await client.fetch(`
    *[_type == "post" && slug.current == $slug][0]{title, "name": author->name, price}
  `, { slug })
}

export default Post

However this productData is not accessible from another page and the react context state is not getting updated. Any idea why this could be happening?


Solution

  • Once you've updated your context value. Please make sure you are using next/link to navigate between pages. Here is details about next/link