'Why do I get an error 'Object is possibly 'undefined' when getting API data in typescript and react?
So I'm getting movie API data in react using typescript, it looks like this:
const [movies, setMovies] = useState<IMovie[]>();
useEffect(() =>{
fetchPopularMovies('popular').then((response) =>{
setMovies(response.data.results);
})
console.log(movies);
}, [])
API function:
export async function fetchPopularMovies(type:string) {
let url: string = `${API_BASE}movie/${type}?api_key=${TMDB_API_KEY}`;
const response = await axios.get<MovieResults>(url);
return response;
}
const few_movies = movies ? movies.slice(1,7) : null;
It's a component which displays recent movies in a slider. I wanted to pass all movies through App component, but I need different movies in different components, so I decided to make different API calls in each component. But the problem is, when I try to write code like: {few_movies.map((movie, key), I get the next error: Object is possibly 'undefined'. And I think maybe the useState sets response data to movies too late, so it's not defined yet. And that's why my page doesn't display anything.
So my question is, how could I make sure the object is not undefined so it could display movies?
Solution 1:[1]
I think your error Object is possibly 'undefined' comes from setting few_movies to null in the statement:
const few_movies = movies ? movies.slice(1,7) : null;
when the API call is happening.
I assume what you want to do is display your component with an empty list while the API call is being processed and then display the list of movies it fetches.
What you can do to achieve that is return an empty array [] instead of null when movies is being fetched.
So, change the initialisation of few_movies to:
const few_movies = movies ? movies.slice(1,7) : [];
and it should solve the issue.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Snigdha Singh |
