6

I am trying to call the currency according to the properties given in the context API, but whenever I call it will get Error: TypeError: Cannot read properties of null (reading 'useContext'). But when I call it in my home page without passing it to getServerSideProps it's working fine. Can someone please help me out to fix this issue?

import { CryptoState } from "../context/cryptoContext"
import { useContext } from "react";

const GetCurrency = async () => {
    const { currency } = await useContext(CryptoState)
    return currency
}

export default GetCurrency
import Head from 'next/head'
import GetCurrency from '../components/getCurrency';

export default function Home(jsonData) {
  console.log(jsonData)

  return (
    <div className="bg-green-100 dark:bg-gray-800 pb-5 h-screen w-screen">
      <Head>
        <title>Crypto</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>

    </div>
  )
}

export async function getServerSideProps(context) {
  const currency = await GetCurrency();

  const response = await fetch(`https://api.coingecko.com/api/v3/coins/markets?vs_currency=${currency}&order=gecko_desc&per_page=10&page=1&sparkline=false&price_change_percentage=24h`)

  return {
    props: {
      jsonData,
    },
  }
}
juliomalves
  • 42,130
  • 20
  • 150
  • 146
Emmanuel uzoezie
  • 433
  • 1
  • 5
  • 18
  • Does this help answer your question: [Nextjs and Context API](https://stackoverflow.com/questions/54127650/nextjs-and-context-api)? – juliomalves May 13 '22 at 18:17

1 Answers1

5

It's about client and server side code. getServerSideProps execute in server side and context is for client side. You will not get client context in server side. You can use swr for client side data fetch. context will work smoothly with swr.

Otherwise you can store the currency in cookies and you can get the value from cookie in server side.

Tamzid Ahmed
  • 576
  • 4
  • 12