Hello, I am trying to use a modified useData hook from the course that has multiple objects inside. In the course, all the data was in the results object, I’m wondering how I would add a second object with data.
JSON example
{"titles":{
"recommend":{
"top": [
{
"title_description": "A young Han Solo tries to settle an old score with the help of his new buddy Chewbacca, a crew of space smugglers and a cunning old friend.",
"title_id": 31536,
"title_name": "Solo: A Star Wars Story"
}
],
"new": [
{
"title_description": " As the remnants of the Resistance flee Kylo Ren and the First Order, Rey seeks out Luke Skywalker – but he wants nothing more to dowith the Force.",
"title_id": 31571,
"title_name": "Star Wars: Episode VIII: The Last Jedi"
}
]
}}}
In my useData, I changed results to recommend. In the test hook, I made for calling it, I added another interface for the two objects and sent that to my tsx.
import { useEffect, useState } from "react";
import testapi from "../Services/api-test";
import { AxiosRequestConfig, CanceledError } from "axios";
interface FetchResponse<T> {
count: number;
recommend: T[];
}
const useData = <T>(
endpoint: string,
requestConfig?: AxiosRequestConfig,
deps?: any[] //dependencies, this is used for querying
) => {
const [data, setData] = useState<T[]>([]);
const [error, setError] = useState("");
const [isLoading, setLoading] = useState(false);
useEffect(
() => {
const controller = new AbortController(); //for cancellations
setLoading(true);
testapi
.get<FetchResponse<T>>(endpoint, {
signal: controller.signal,
...requestConfig,
})
.then((res) => {
setData(res.data.recommend);
setLoading(false);
})
.catch((err) => {
if (err instanceof CanceledError) return;
setError(err.message);
setLoading(false);
});
return () => controller.abort();
},
deps ? [...deps] : []
);
return { data, error, isLoading };
};
export default useData;
useTest hook
export interface Items {
top: Test;
new: Test;
}
export interface Test {
title_description: string;
title_id: number;
title_name: string;
}
//Hook Name = function => useData hook <Object> ("/endpoint")
const useTest = () => useData<Items>("/titles");
export default useTest;
When I try to map, I get an error in console saying “data.map? is not a function”
Map in tsx:
{error && <div>{error}</div>}
{data?.map((title) => (
<ul key={title.top.title_id} style={{ margin: 0, padding: 0 }}>
<div className={styles.title} onClick={() => navigate("/title")}>
{title.top.title_name}
</div>
</ul>
))}
Is it with how the JSON is set up? Trying to map to an object and not an array?
Thanks!