How to use useContext data with properties

Viewed 131

I'm using useContext in a component page, and it correctly gets datas through useContext in a type of a property.

colorContex.js

import { createContext, useEffect, useState, useContext } from 'react';

// create context object
export const ColorContext = createContext({});

export const ProductsProvider = (props) => {
  const [data, setData] = useState(null);
  useEffect(() => {
    async function fetchAPI() {
      const res = await fetch(url);
      const posts = await res.json();
      setData(posts);
    }
    fetchAPI();
  }, []);
  return <ColorContext.Provider value={data}>{props.children}</ColorContext.Provider>;
};

headerDefault.tsx

  const colors = useContext(ColorContext);
  console.log(colors);
  // the data shows up correctly in console log
  const colorData = colors.response;
  // the error message( the property doesn't exist type {}. )

Google development

the data is correct and a type of property. How can I get property datas?

ColorData

1 Answers

The problem here is this line:

export const ColorContext = createContext({});

TypeScript infers the context type from this line and {} does not have a .response property.

To fix this, define the type of your Context:

type ColorContextType = null | {
  response: {
    result_info: any, // TODO: type this correctly
    result_list: any[],  // TODO: type this correctly
  }
}

export const ColorContext = createContext<ColorContextType>(null);

export const ProductsProvider = (props) => {
  const [data, setData] = useState<ColorContextType>(null);

Related