I'm refactoring my React app to Typescript and so far so good. I'm on my last component, the one that fetches the API data and I'm trying to understand why these type errors aren't resolving. I used https://jvilk.com/MakeTypes/ to help scaffold the interfaces correctly.
Object is possibly 'null' twice for error & stories (commented lines below)
Parameter '___' implicitly has an 'any' type. twice for story & idx (commented lines below)
I'm having trouble with this API call component. What am I missing?
import React, { FC, ReactElement, useEffect, useState } from "react";
import Story from "./Story";
export interface NewsProps {
results?: (ResultsEntity)[] | null;
}
export interface ResultsEntity {
section: string;
title: string;
abstract: string;
url: string;
multimedia?: (MultimediaEntity)[] | null;
}
export interface MultimediaEntity {
url: string;
caption: string;
}
const News: FC<NewsProps> = ({results:ResultsEntity}):ReactElement => {
const [error, setError] = useState(null);
const [stories, setStory] = useState(null);
useEffect(() => {
const getCurrentPage = () => {
const url = new URL(window.location.href);
const page = url.pathname.split("/").pop();
return page ? page : "home";
};
const section = getCurrentPage();
fetch(
`https://api.nytimes.com/svc/topstories/v2/${section}.json?api-key=4fzCTy6buRI5xtOkZzqo4FfEkzUVAJdr`
)
.then((res) => res.json())
.then((data) => {
setTimeout(() => setStory(data), 1500);
})
.catch((error) => {
console.log("Error", error);
setError(error);
});
}, []);
if (error) {
return <div>Error: {error.message}</div>; /// "Object is possibly 'null'" (for error)
} else
if (!stories) {
return <div>Loading...</div>
} else {
return (
<>
<ul className="stories">
{stories.results.map((story, idx) => { // "Object is possibly 'null'" (for stories)
// Parameter '__' implicitly has an 'any' type (for idx & story)
return (
<Story
key={idx}
title={story.title}
abstract={story.abstract}
img={
story &&
story.multimedia &&
story.multimedia[0] &&
story.multimedia[0].url
? story.multimedia[0].url
: null
}
alt={
story &&
story.multimedia &&
story.multimedia[0] &&
story.multimedia[0].caption
? story.multimedia[0].caption
: null
}
link={story.url}
/>
);
})}
</ul>
</>
);
}
}
export default News;