I'm struggling with providing data via useContext. I know how to create useContext in React, but I was trying several times to do the same in Next.js with TypeScript.
Could someone please help me. Here below 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 plan is to get data from my backend node.js (already deployed on heroku server). I've tried to do that with useEffect in useContext external file, but... lots of different errors because of TypeScript.
here below my Context.jsx file:
import React, { createContext, useState, useEffect } from "react";
// create context
const CodeContext = createContext();
const CodeContextProvider = ({ children }) => {
// the value that will be given to the context
const [blog, setBlogs] = useState(null);
// fetch a user from a fake backend API
useEffect(() => {
const fetchData = () => {
// this would usually be your own backend, or localStorage
// for example
fetch(`https://node-test-mongo.herokuapp.com/api/blog`)
.then((response) => {
return response.json();
})
.then((data) => {
setBlogs(data.blogs)
})
};
fetchData().catch(console.error);
}, []);
return (
// the Provider gives access to the context to its children
<CodeContext.Provider value={blog}>
{children}
</CodeContext.Provider>
);
};
export { CodeContext, CodeContextProvider };
I just need have data (title and text) from my api and to have posibility to take it everywhere I want.
Thanks in advance. I'll be really appreciate for help:)