0

First let me apologise for my horrible ability at formatting. Secondly, I know its a real mess down there. As things grew in complexity so did undertanding the properway to layout this code. That being said, this is where im currently at.

I used three diffrent API links to gather data for 3 seperate states. 1 is search results, another is trending, and the other is upcoming. After I displayed alot of it's useful data, I wanted to add a feature where I can click on any movie image and be taken to the website that I can buy or watch the movie.
MovieDatabase APi has another link for that but you need to include the ${movieID} inside the link. This link will give you the data that holds the actual link on where to watch or buy the movie. I wanted to obtain that link and set each individual movie with their own provider link. (the link that takes you to the site where you can watch or buy the movie). So i figured id start attempting this with the trending movies.
To do this I figured I could go into the useEffect call for the trending movies and take the state thats set for trending and get an array if the movie ID's...and I did...with trending.map((item) => setMovieId(item.id)); then I made a new function called ProviderLink and added that movieId as a parameter to the link that will give me each indvidual movie's providerLink. (the link that tells you where to buy or watch the movie)...again I Fetched the new link with this new movieId parameter now in the link, i got the data, I set it to a new state and tried to apply that state in an anchor tag below where i was rendering all the movies. I wrapped each movie list item in an <a href={providerLink}></a> thinking that this would set each movie up with their proper provider link. but it doesnt work...I get an error telling me that it failed to fetch, it's not even including the ID in the list like I need it too. If you need the API key to try it out let me know. or stop at the moviedatabase site and grab one quick.

import React, {useState, useEffect} from 'react';

const SearchBar = () => {

const [search, setSearch] = useState([]);
const [input, setInput] = useState('');
const [trending, setTrending] = useState([]);
const [upcoming, setUpcoming] = useState([]);
const [providerlink, setProviderlink] = useState('');
 const [movieId, setMovieId] = useState([]);

 

// Input Field
const onUserInput = ({target}) => {
    setInput(target.value);

};


// On page load Fetch trending movies
useEffect(() => { 

    const trendUrl = "https://api.themoviedb.org/3/trending/movie/week?api_key=fde5ddeba3b7dec3fc1f51852ca0fb95";
fetch(trendUrl)
.then((response) => response.json())
.then((data) => {
   setTrending(data.results);
})
.catch((error) => {
    console.log('Error!! Data interupted!:', error)
});
 
trending.map((item) => setMovieId(item.id));


}, [trending]);


// MovieProviderLink
useEffect(() => { 
    const url = 
    `https://api.themoviedb.org/3/movie/${movieId}/watch/providers?api_key=fde5ddeba3b7dec3fc1f51852ca0fb95`;
    fetch(url)
    .then((res) => 
      res.json()
    ).then((res) =>  
         setProviderlink(res.results));

  //Gives movie ID and adds it to properlink
    
}, [movieId]);



useEffect(() => {
    const upcomingUrl = "https://api.themoviedb.org/3/movie/upcoming?api_key=fde5ddeba3b7dec3fc1f51852ca0fb95";

    fetch(upcomingUrl)
    .then((response) => response.json())
    .then((data) => {
       setUpcoming(data.results);
    })
    .catch((error) => {
        console.log('Error!! Data interupted!:', error)
    });
});


//  Api Call 
const SearchApi = (event) => {
    const aUrl = "https://api.themoviedb.org/3/search/movie?api_key=fde5ddeba3b7dec3fc1f51852ca0fb95";
   const newUrl = aUrl +'&query=' + input;
 event.preventDefault();
       
    fetch(newUrl)
    .then((response) => response.json())
    .then((data) => {
       setSearch(data.results);
        
    })
    .catch((error) => {
        console.log('Error!! Data interupted!:', error)
    })

    };
    
      return (
        //   Heading
<div>
    <div className="container">
        <h1>Movie Search Extravaganza!</h1>

        {/* Input Field and Button Form */}
      <form onSubmit={SearchApi}>
        <input value={input} onChange={onUserInput} type="text"  className="searchbar" aria-label="searchbar" placeholder="search" required/>
        <br></br>
        <button type="submit"  aria-label="searchbutton" className="searchBtn">Movie Express Search</button>
      </form>
     </div>



    <div className="byName-container">
        <h1 className="row-label" tabIndex="0">Movies Related To Your Search</h1>
      <ul className="flexed-search">
          
          {search.map((item) => 
          <div className="poster-container" key={item.id}>
          <li className="list-item">
              <a href="www.google.com" onclick={((event) => {event.preventDefault()})}>
           <img className="image-element"  tabIndex="0" alt="movie poster" title={`--Title: ${item.title}--  --Description:    ${item.overview}--  --Vote Average: ${item.vote_average}`} aria-label={item.title} src={`https://image.tmdb.org/t/p/w500${item.poster_path}`} />
           </a>
          <h3 className="posterTitle">{item.title}</h3>
          </li>
          </div>
       )}
      </ul>
        </div>
 

<div className="trending-container">
    <h1 className="row-label" tabIndex="0">This Weeks Trending Tittles</h1>
    <ul className="flexed-trending">
    {trending.map((it) => 
    
    <div className="poster-container" key={it.id}>
        <a href={providerlink}>
    <li className="list-item"> <img className="image-element" tabIndex="0" aria-label={it.title} title={`--Title: ${it.title}--  --Description:    ${it.overview}--  --Vote Average: ${it.vote_average}`} alt="movie poster" src={`https://image.tmdb.org/t/p/w500${it.poster_path}`} />
     <h3 className="posterTitle">{it.title}</h3>
     
    </li>
    </a>
    </div>
    
    )}
    </ul>
</div>


<div className="upcoming-container"> 
<h1 className="row-label" tabIndex="0">Upcomming Movies</h1>
 <ul className="flexed-upcoming">
 {upcoming.map((inn) => 
 <div className="poster-container" key={inn.id}>
 <li className="list-item">
 <img className="image-element" tabIndex="0" alt="movie poster" aria-label={inn.title} title={`--Title: ${inn.title}--  --Description:    ${inn.overview}--  --Vote Average: ${inn.vote_average}`} src={`https://image.tmdb.org/t/p/w500${inn.poster_path}`} />

 <h3 className="posterTitle">{inn.title}</h3>
 </li>
 </div>
 )}
 </ul>


</div>
        

        </div>


    )
};

export default SearchBar;```
Alex Smith
  • 47
  • 7

1 Answers1

0

You have to create a loop around your JSON array that you get from your API call to display your desired content. E.g. if you have a section with trending, you loop through your trending JSON array and display the content in a structure you want. I don't know the return values, but you can probably do something like {movie.name} or something like that. Inside the initial loop, you can create another loop that iterates through the providers API.

A sugar code notation would be something like this:

var trendingMoviesContainer = document.querySelector('your_selector_here');
var html = "";
for(let movie in trending_array){
    html += '<div ....>{movie.id}</div>';
    html += '<div ...>{movie.name}</div>';
    //etc...
    let providersUrl = "https://api.themoviedb.org/3/movie/{movie.id}/watch/providers?api_key="
    // rest of your fetch data logic...
    
    for(let provider in providers_array) {
        html += '<div ...>{provider.name}</div>';
        html += '<div ...>{provider.link}</div>';
        //etc...
    }
    // inject trending movies structure into container
    trendingMoviesContainer.append(html); 
}
Martin
  • 1,849
  • 1
  • 11
  • 17
  • THank you for your repsonse Martin, Im just React so the way I would be doing what your showed would be a bit diffrent but at the same time you have the right Idea so im trying to incorperate what you did into my project. Ill let you know how it goes. – Alex Smith Apr 02 '21 at 13:41
  • So i wrapped each image in trending also with an anchor tab with an href to www.google.com but when I click an image then it just refreshes my page. In react dev tools it says google is the href location but it never eactually takes me to google.com any thoughts?> – Alex Smith Apr 02 '21 at 14:52
  • @AlexSmith How did you implement it precisely? Could you update your question with your current source code? Are you utilizing the React router? – Martin Apr 02 '21 at 15:17
  • yeah ill update it now, i didnt use react router yet, I was thinking about using it after all the trouble ive been having thus far. theres alot going on right now that im trying to figure out. ill do my best to explain, ill update my source code now – Alex Smith Apr 02 '21 at 21:42
  • @AlexSmith quite odd since traditional anchor tags should work fine in React. Try have a look at this post and see if there is anything of use: https://stackoverflow.com/questions/42914666/react-router-external-link – Martin Apr 02 '21 at 23:06