skip to Main Content

So, I’ll try to keep this as short as possible even tho I don’t know how possible it’s gonna be. I’m trying to create an app that shows the 20 top rated movies and 20 upcoming movies on the front page when you open the app. Easy enough. I also have a search bar at the top where I can search for movies and get the results back. One of the issues is that I’m quite new to React and Frontend development in general (and programming too, I haven’t really been programming for long) and I just don’t know how to solve the issue I have.

The issue is that, when I search for a movie, I want React to render a different component and take me to a different route, for example http://localhost:3000/searchresults/:keyword or something like that. I know how to set that up in App.js, with the routes and all that, but I just can’t get it to work. Most recently, the issue is that I’m getting some sort of an error that the results I’m getting back from the API don’t exist, or that they’re undefined. Again, I’m not very good at this so I’m having some trouble with understanding what’s wrong and what do I actually have to do to fix the issue.

If anyone could and would want to help, I’d love to hear your suggestions! I can give you the link to my GitHub repository so that you can download the code and maybe identify the issue in that way.

To address a couple of points before someone points them out, I am very much aware that my code looks quite ugly, there’s a lot of things that could and should be broken up in separate components or even some things that don’t even make sense. I’ve been using ChatGPT to help me out with stuff and it’s been quite useful so far, except that I’m stuck now and don’t know how to solve this issue. Also, I’m aware that you should normally hide your API key or API Read Access Token, but I don’t think I need to hide it here. I’ve been trying some stuff out and that’s why some code is commented out, maybe even if it shouldn’t be commented out, or it simply shouldn’t be there in the first place.

I am very thankful to anyone who could help me out with this. Right now, I’m getting an error that says "TypeError: Cannot read properties of undefined (reading ‘results’)" in the 30th line of code in my Searchfield2 component.

https://github.com/IITheGameII/movie-app

I tried a lot of different things, mostly with ChatGPT’s suggestions cause I just don’t know how to do it on my own and I haven’t been able to find a solution online.

2

Answers


  1. I found that you are not actually returning the result of res.json() from the .then() block.

    You need to return that promise so that you can call .then() on it.

    The 28’th line in your code,

    .then(res => { res.json() })

    should be like

    .then(res => res.json()) or .then(res => { return res.json() }).

    Note: Refer the code in line:50 inside loadMoreResults
    function in the same file.

    Login or Signup to reply.
  2. My approach would be to just navigate to the results page in your searchfield2 component:

    const handleSearch = (e) => {
      navigate(`/search/${query}`);
    };
    

    And then do the api call on your results page:

    import { useState, useEffect } from "react";
    import { Link } from "react-router-dom";
    import { useParams } from "react-router-dom";
    
    function Searchresult() {
    const { keyword } = useParams();
    const [results, setResults] = useState(null);
    const [totalResults, setTotalResults] = useState(null);
    
    useEffect(() => {
        const options = {
        method: "GET",
        headers: {
            accept: "application/json",
            Authorization:
            "Bearer eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJlMTZkNjc4NTRlMjE4MjcxOThkNzU5OGUwZmIwYjBmZCIsInN1YiI6IjY1MTZhZmJmYTE5OWE2MDEzOGI4MWU0NyIsInNjb3BlcyI6WyJhcGlfcmVhZCJdLCJ2ZXJzaW9uIjoxfQ.JcDppgMNSax-FO2JJLKXhXghF3eSv4E0ulOCtWDdhhg", // Replace with your API key
        },
        };
        fetch(
        `https://api.themoviedb.org/3/search/movie?query=${keyword}&include_adult=false&language=en-US&page=1`,
        options
        )
        .then((res) => {
            return res.json();
        })
        .then((res) => {
            setResults(res.results);
            setTotalResults(res.total_results);
        })
        .catch((err) => {
            console.error(err);
        });
    }, []);
    
    return (
        <div>
        {totalResults !== null && <p>Total Results Found: {totalResults}</p>}
        <h1>Search results for: {keyword}</h1>
        {results && results.length > 0 ? (
            results.map((movie) => (
            <>
                <Link to={`/movie/${movie.id}`} key={movie.id}>
                <img
                    src=`https://image.tmdb.org/t/p/w300/${movie.poster_path}`}
                    alt={movie.title}
                />
                <h2>{movie.title}</h2>
                </Link>
                <p>{movie.overview}</p>
                <br />
                <br />
            </>
            ))
        ) : (
            <p></p>
        )}
        </div>
    );
    }
    
    export default Searchresult;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search