I am fetching data from the OMDB API and saving this data to a state. However, I am running into 2 questions/issues:
- How can I destructure the data I receive while also renaming it and then saving these to state?
- How can I only save specific properties to the state object?
Details:
When I fetch from the OMBD API, I receive a large response object with more properties than I will use. I want to only save specific properties within my state and also to rename these properties.
The response from:
useEffect(() => {
const getMovie = async () => {
const res = await fetch(
`http://www.omdbapi.com/?apikey=${API_KEY}&i=${selectedId}`
);
const data = await res.json();
// Destructuring and setting state here
};
getMovie();
}, []);
This response contains more data than I will end up needing to use for my state object. The properties are also all capitalized when I would like to rename them to lowercase in order to follow a more standardized naming convention. (See below type)
export interface MovieDetailType {
title: string;
year: string;
poster: string;
runtime: string;
plot: string;
imdbRating: string;
released: string;
actors: string[];
director: string;
genre: string;
}
How do I destructure and rename the response (to lowercase) so I only store the particular properties listed in my above type?
const [movie, setmovie] = useState<MovieDetailType>();
...
<header>{movie.title}</header>
<p>{movie.plot}</p>
/// etc
2
Answers
A simple solution would be to create a new object possessing the property names of interest and their respective values to the server-side model. For example: