How to share dynamic state with React Context in Next.js

Viewed 21

I am trying to share information (from an API) and use it between different pages using React Context in Next.js.

I have a table that contains transactions data from an API. My goal is that when the user clicks on any row, is redirected to another tab with more information about that specific transaction.

I actually can log the transaction data in the console, but when i log it in a different tab, it has its default value ({})

path: src/pages/_app

import { TransactionProvider } from 'context/TransactionContext'

const MyApp = ({ Component, pageProps }) => {
  return (
    <TransactionProvider>
      <Component {...pageProps} />
    </TransactionProvider>
  )
}

export default MyApp

path: src/context/TransactionContext.js

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

const TransactionContext = createContext()

export const TransactionProvider = ({ children }) => {
  const [transactionData, setTransactionData] = useState({})
  return (
    <TransactionContext.Provider
      value={{ transactionData, setTransactionData }}
    >
      {children}
    </TransactionContext.Provider>
  )
}

export const useTransactionContext = () => {
  const context = useContext(TransactionContext)

  if (!context) throw new Error('Transaction context is not defined here!!')

  return context
}

I think that the state losing can be because of something like change to another tab and unmount the component (though it is saved in a Context) or something similar.

TLDR: i need to share dynamic state (using useState hook) betweeen different pages AND using React Context.

0 Answers
Related