I am facing challenges with using useContext to provide data. While I understand how to implement useContext in React, I have been struggling to do the same in Next.js with TypeScript.
Could someone please assist me? Below is my _app.jsx
code:
import { AppProps } from 'next/app';
import Head from 'next/head';
import React, { useState } from 'react';
import '../styles/globals.css';
import { CodeContextProvider } from '../shared/context/Context.jsx'
function MyApp({ Component, pageProps }: AppProps): JSX.Element {
const [context, setContext] = useState("Kyiv");
return (
<CodeContextProvider>
<Head>
<title></title>
<link rel="icon" href="/favicon.ico" />
</Head>
<Component {...pageProps} />
</CodeContextProvider>
)
}
export default MyApp;
My goal is to fetch data from my Node.js backend (already deployed on a Heroku server). I attempted to use useEffect in an external file within useContext but encountered various TypeScript errors.
Here is my Context.jsx file:
import React, { createContext, useState, useEffect } from "react";
const CodeContext = createContext();
const CodeContextProvider = ({ children }) => {
const [blog, setBlogs] = useState(null);
useEffect(() => {
const fetchData = () => {
fetch(`https://node-test-mongo.herokuapp.com/api/blog`)
.then((response) => {
return response.json();
})
.then((data) => {
setBlogs(data.blogs)
})
};
fetchData().catch(console.error);
}, []);
return (
<CodeContext.Provider value={blog}>
{children}
</CodeContext.Provider>
);
};
export { CodeContext, CodeContextProvider };
I simply need to retrieve data (title and text) from my API and be able to access it anywhere within my application.
Thank you in advance for any assistance provided. I truly appreciate your help :)