I'm trying to use React's Context API as well as Hooks with fetching data.
I'm coding [createContext] like below, but it doesn't work.
import { createContext, useEffect } from "react";
export const ColorContext = createContext({});
export const ProductsProvider = props => {
useEffect(() => {
(async() => {
const res = await fetch('http://localhost:3000/api/categories')
const posts = await res.json()
return { props: { datas: posts } }
})
})
return(
<ColorContext.Provider value={props.datas}></ColorContext.Provider>
)
}
And here're I'm trying to use [useContext]. This's a default header as a component.
import { ColorContext } from '../../src/colorContext';
import { useContext } from "react";
export default function HeaderDafault(props) {
const colors = useContext(ColorContext);
console.log(colors);
return (
<header className={`h-10 px-5 flex items-center relative`}>
</header>
);
}
There's no errors, but there's nothing in console log. I think the way i'm using [createContext] is wrong, but i can't find my mistakes.
The problem is that you are not storing the data somewhere after fetching it in the
useEffecthook.useContextis used along withuseStateto store and provide the data to other components.Do this instead: