how to use useEffect and useContext with fetching data?

3.1k views Asked by At

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.

1

There are 1 answers

4
Amit On

The problem is that you are not storing the data somewhere after fetching it in the useEffect hook.

useContext is used along with useState to store and provide the data to other components.

Do this instead:

import { createContext, useEffect, useState } from "react";

export const ColorContext = createContext({});

export const ProductsProvider = (props) => {
  const [data, setData] = useState(null);
  useEffect(() => {
    async function fetchAPI() {
      const res = await fetch("http://localhost:3000/api/categories");
      const posts = await res.json();
      setData(posts);
    }
    fetchAPI();
  }, []);
  return <ColorContext.Provider value={data}></ColorContext.Provider>;
};