Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unexpected type conversion of react context class to object type in NextPage #54562

Closed
1 task done
graykode opened this issue Aug 25, 2023 · 2 comments
Closed
1 task done
Labels
bug Issue was opened via the bug report template. Lazy Loading Related to Next.js Lazy Loading (e.g., `next/dynamic` or `React.lazy`). stale The issue has not seen recent activity.

Comments

@graykode
Copy link

graykode commented Aug 25, 2023

Verify canary release

  • I verified that the issue exists in the latest Next.js canary release

Provide environment information

Operating System:
      Platform: darwin
      Arch: arm64
      Version: Darwin Kernel Version 21.6.0: Thu Jun  8 23:56:13 PDT 2023; root:xnu-8020.240.18.701.6~1/RELEASE_ARM64_T6000
    Binaries:
      Node: 18.16.1
      npm: 9.5.1
      Yarn: 1.22.19
      pnpm: N/A
    Relevant Packages:
      next: 13.4.19
      eslint-config-next: 13.4.19
      react: 18.2.0
      react-dom: 18.2.0
      typescript: 5.1.6
    Next.js Config:
      output: N/A

Which area(s) of Next.js are affected? (leave empty if unsure)

Dynamic imports (next/dynamic)

Link to the code that reproduces this issue or a replay of the bug

https://github.com/clober-dex/coupon.finance/blob/fix/class-type-context/pages/deposit/%5Bsymbol%5D.tsx#L53

To Reproduce

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <CurrencyProvider>
      <Component {...pageProps} />
    </CurrencyProvider>
  )
}
type CurrencyContext = {
  balances: { [key in `0x${string}`]: BigDecimal }
}

const Context = React.createContext<CurrencyContext>({
  balances: {},
})

export const CurrencyProvider = ({ children }: React.PropsWithChildren<{}>) => {
  const { address: userAddress } = useAccount()

  const { data: balances } = useQuery(['balances', userAddress], async () => {
    const currencies = await fetchCurrencies()
    if (!userAddress) {
      return {}
    }
    const results = await readContracts({
      contracts: currencies.map((currency) => ({
        address: currency.address,
        abi: IERC20__factory.abi,
        functionName: 'balanceOf',
        args: [userAddress],
      })),
    })
    return results.reduce((acc, { result }, i) => {
      const currency = currencies[i]
      return {
        ...acc,
        [currency.address]: BigDecimal.fromIntegerValue(
          currency.decimals,
          (result ?? 0n).toString(),
        ),
      }
    }, {})
  })

  return (
    <Context.Provider
      value={{
        balances: balances ?? {},
      }}
    >
      {children}
    </Context.Provider>
  )
}

export const useCurrencyContext = () =>
  React.useContext(Context) as CurrencyContext
  export const getServerSideProps: GetServerSideProps<{
  asset?: Asset
}> = async ({ params }) => {
  const assets = await fetchAssets()
  const asset = assets.find(
    ({ underlying }) => underlying.symbol === params?.symbol,
  )
  return {
    props: { asset },
  }
}

const Deposit: NextPage<
  InferGetServerSidePropsType<typeof getServerSideProps>
> = ({ asset }) => {
  const { balances } = useCurrencyContext()
  const [selected, _setSelected] = useState(0)
  const [value, setValue] = useState('')

  const router = useRouter()

  const setSelected = useCallback(
    (value: number) => {
      _setSelected(value === selected ? value - 1 : value)
    },
    [selected],
  )
  console.log('asset', asset)
  console.log('balances', balances)
  console.log('balance of', balances[asset?.underlying.address ?? zeroAddress].toFixed(2)) <- error

Describe the Bug

In the context of a Next.js application, an unexpected behavior has been observed where the class type defined for a React context undergoes a conversion to an object type specifically when accessing the NextPage directly. The behavior is inconsistent with the expected behavior when the application starts from the MyApp component.

Expected Behavior

The class type assigned to the React context should remain consistent and unchanged, regardless of whether the application is started from the MyApp component or if the user navigates directly to the NextPage component.

Which browser are you using? (if relevant)

No response

How are you deploying your application? (if relevant)

No response

@graykode graykode added the bug Issue was opened via the bug report template. label Aug 25, 2023
@github-actions github-actions bot added the Lazy Loading Related to Next.js Lazy Loading (e.g., `next/dynamic` or `React.lazy`). label Aug 25, 2023
@nextjs-bot
Copy link
Collaborator

This issue has been automatically marked as stale due to two years of inactivity. It will be closed in 7 days unless there’s further input. If you believe this issue is still relevant, please leave a comment or provide updated details. Thank you.

@nextjs-bot nextjs-bot added the stale The issue has not seen recent activity. label Feb 20, 2025
@nextjs-bot
Copy link
Collaborator

This issue has been automatically closed due to two years of inactivity. If you’re still experiencing a similar problem or have additional details to share, please open a new issue following our current issue template. Your updated report helps us investigate and address concerns more efficiently. Thank you for your understanding!

@nextjs-bot nextjs-bot closed this as not planned Won't fix, can't repro, duplicate, stale Feb 28, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Issue was opened via the bug report template. Lazy Loading Related to Next.js Lazy Loading (e.g., `next/dynamic` or `React.lazy`). stale The issue has not seen recent activity.
Projects
None yet
Development

No branches or pull requests

2 participants