Reputation: 79
I'm trying to add TypeScript interface types to the JSON data I'm pulling in. I'm currently receiving the following error in relation to my MachineDetail.tsx file:
Property 'data' does not exist on type 'APIContextInterface | null'.
MachineDetail.tsx (line below is where it's throwing the error)
const { data, isLoading } = useContext(APIContext);
apiContext.tsx (where I'm pulling in API data and storing it in Context)
My TypeScript interface and the Context where I'm holding the data:
import React, { useState, useEffect, createContext } from "react";
import axios from "axios";
interface APIContextInterface {
category: string;
product_details: {
id: number;
category: string;
model: string;
power: number;
operating_weight: number;
description: string;
image: string;
};
}
export const APIContext = createContext<APIContextInterface | null>(null);
export default function APIContextProvider({ children }) {
// Initialize state
const [data, setData] = useState([]);
const [isLoading, setLoading] = useState(true);
// Fetch data
useEffect(() => {
let url = "../db.json";
axios
.get(url)
.then(function (response) {
setData(response.data.machines);
setLoading(false);
})
.catch((error) => console.log(error));
}, []);
return (
<APIContext.Provider value={{ data, isLoading }}>
{children}
</APIContext.Provider>
);
}
The JSON data is structured like so:
{
"machines": [{
"category": "category name",
"product_details": [{
"id": 1,
"category": "category name",
"model": "224X3",
"power": 67.1,
"operating_weight": 5849,
"description": "desc goes here",
"image": "url-link"
},
],
},
]
}
Upvotes: 0
Views: 937
Reputation: 2747
This error is raised because After creating context, your useState can create separate state instead of adding it into your created context.
You can find solution from this answer : Passing state with useContext in Typescript
Upvotes: 0
Reputation: 916
It is because you defined APIContext
to be a context containing APIContextInterface | null
:
export const APIContext = createContext<APIContextInterface | null>(null);
while you actually provided values of another type. Remember the type you give to createContext
is always the type you should provide. Hence you should write
export const APIContext = createContext<{
data: APIContextInterface[],
isLoading: boolean
} | null>(null);
instead so as to match your actual data.
Upvotes: 2