useContext on TypeScript, how?😢😥 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

useContext on TypeScript, how?😢😥

https://www.sololearn.com/compiler-playground/ctO3yvHpfvyj My problem is, I can't call the properties of my created context. Please be soft to correct me since I already know that I'm having a hard time in useContext hooks and using types/interface of TypeScript. Please check this code https://www.sololearn.com/compiler-playground/ctO3yvHpfvyj EDIT: This is working on latest version of TypeScript; it's just I'm putting my code into SPFx of Microsoft which uses old version of Typescript. //---------------THE ERROR-------------------- [08:04:51] Error - [tsc] src/webparts/onlineShop/components/header/ShopHeader/HeaderImage.tsx(12,21): error TS2339: Property 'timer' does not exist on type 'unknown'. [08:04:51] Error - [tsc] src/webparts/onlineShop/components/header/ShopHeader/HeaderImage.tsx(23,60): error TS2339: Property 'images' does not exist on type 'unknown'.

8th Nov 2022, 11:27 PM
Jonathan P. Jundarino
Jonathan P. Jundarino - avatar
1 Answer
0
import React, { createContext, useContext } from 'react'; interface YourContextData { timer: number; images: string[]; } const YourContext = createContext<YourContextData | undefined>(undefined); const HeaderImage: React.FC = () => { const contextData = useContext(YourContext); if (!contextData) { return null; } const { timer, images } = contextData; // Now we can use 'timer' and 'images' without issue TypeScript return ( // JSX of ur component here ); }; export { YourContext, HeaderImage };
26th Feb 2024, 11:01 AM
Knight
Knight - avatar