skip to Main Content

I am fetching data from the OMDB API and saving this data to a state. However, I am running into 2 questions/issues:

  1. How can I destructure the data I receive while also renaming it and then saving these to state?
  2. 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();
  }, []);

Response from Fetch
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


  1. 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:

    const objMovie = { title: data.Title, year: data.Year };
    setmovie(objMovie);
    
    Login or Signup to reply.
    • You can call the setmovie and using your interface assign the relevant values
    • It appears (in your image) that actors come back as one string so you need to split into an array
    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
            setmovie({
                title: data.Title,
                year: data.Year,
                poster: data.Poster,
                runtime: data.Runtime,
                plot: data.Plot,
                imdbRating: data.ImdbRating,
                released: data.Released,
                actors: data.Actors.split(", "), //Appears to be one string in the response
                director: data.Director,
                genre: data.Genre,
            }) 
        };
    
        getMovie();
    }, []);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search