2

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

Yuzu
  • 59
  • 1
  • 8

1 Answers1

2

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);

Taxel
  • 3,859
  • 1
  • 18
  • 40
  • Thank you. I edited my code, and there's an another error that says 'TypeError: Cannot read properties of null (reading 'response')' even though there's a data in response. – Yuzu Apr 08 '22 at 11:28
  • If you are 100% certain it can never be `null`, use the [non-null assertion operator](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html#non-null-assertion-operator): `colors!.response`. Otherwise check if it is not null: `if(colors !== null){colors.response etc}` – Taxel Apr 08 '22 at 11:31