skip to Main Content

I’m working on a React project and I’m having trouble displaying data fetched from an API in my Movies component. The data is correctly logged in the console, but it doesn’t show up on the page. I need some help figuring out why.

Here’s the code for my API call:

import axios from 'axios';

const BASE_URL = 'http://127.0.0.1:5000';

export const getMovie = async (mood) => {
    try {
        console.log('Fetching movies for mood:', mood);
        const response = await axios.get(`${BASE_URL}/recomendar`, {
            params: { mood },
            headers: {
                Authorization: `Bearer ${localStorage.getItem('token')}`
            }
        });
        console.log(response.data);
        return response.data;
    } catch (error) {
        console.error('Error fetching movies:', error);
        throw error;
    }
};

And here’s the Movies component where I’m trying to display the data in HTML:

import React, { useEffect, useState } from "react";
import { getMovie } from "../services/api";

const Movies = ({ mood }) => {
  const [movies, setMovies] = useState([]);

  useEffect(() => {
    const fetchMovies = async () => {
      if (mood) {
        try {
          const moviesData = await getMovie(mood);
          console.log(moviesData);  // This logs the data correctly
          setMovies(moviesData);
        } catch (error) {
          console.error("Error fetching movies:", error);
        }
      }
    };

    fetchMovies();
  }, [mood]);

  return (
    <div style={{ padding: "128px" }}>
      <h3>Movies</h3>
      <ul>
        {movies.map((movie) => (
          <li key={movie.id}>
            <div>{movie.title}</div>
            <div>{movie.genre}</div>
          </li>
        ))}
      </ul>
    </div>
  );
};

export default Movies;

How the data is coming:
enter image description here

In the Html, the ul tag is empty
enter image description here

I am getting the mood from the user selection through the Onclick in the Main component

import { Link } from "react-router-dom";

import Section from "./Section";
import Button from "./Button";
import curve from "../assets/curve.png";
import { moods } from "../constants/mood";
import { getMovie } from "../services/api";
import { useState } from "react";

export const Main = () => {


  const [movies, setMovies] = useState([]);

  const handleMoodSelect = async (mood) => {
    try {
      const moviesData = await getMovie(mood);
      setMovies(moviesData);
    } catch (error) {
      console.error('Error fetching movies:', error);
    }
  };

  return (
    <Section className="pt-[12rem] -mt-[5.25rem] mb-8" customPaddings id="main">
      <div className="container relative">
        <div className="relative z-1 max-w-[62rem] mx-auto text-center mb-[3.875rem] md:mb-20 lg:mb-[6.25rem]">
          <h1 className="h1 mb-6">
            Descubra filmes incríveis com base no seu{" "}
            <span className="inline-block relative h1">
              humor
              <img
                src={curve}
                className="absolute top-full left-0 w-full xl:-mt-2"
                width={624}
                height={28}
                alt="Curva"
              />
            </span>
          </h1>
          <span className="inline-block relative h1">
            <img
              src={curve}
              className="absolute top-full left-0 w-full xl:-mt-2"
              width={624}
              height={28}
              alt="Curva"
            />
          </span>
          <p className="body-1 max-w-3xl mx-auto mb-6 text-n-2 lg:mb-8">
            A pergunta é: Como você está se sentindo hoje?
          </p>
          <Button white>Começar agora</Button>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-x-4 gap-y-4">
          {moods.map((mood) => (
            <button onClick={() => handleMoodSelect(mood.title)}>
            <Link to={`/movies/${mood.title}`}>
              <div className="mb-2 p-4 rounded-lg relative">
                <div
                  className="absolute inset-0 cursor-pointer"
                  style={{
                    borderRadius: "5px",
                    padding: "2px",
                    background:
                      "linear-gradient(225deg, #FFC876, #79FFF7, #9F53FF, #FF98E2, #FFC876)",
                    WebkitMask:
                      "linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0)",
                    WebkitMaskComposite: "xor",
                    maskComposite: "exclude",
                    position: "absolute",
                    content: '""',
                    inset: 0,
                  }}
                />
                {mood.title} {mood.emoji}
              </div>
            </Link>
          </button>
          ))}
        </div>
      </div>
    </Section>
  );
};

2

Answers


  1. The problem is not in the code, all is good

    You need to investigate what hinders. Try fix all warning linked with this page

    Login or Signup to reply.
  2. The problem was that the Movies component was used as a page rendered by the router. mood was a route parameter thus changed the code to:

    import { useParams } from 'react-router-dom';
    
    
    const Movies = () => {
        const { mood } = useParams();
    
        const [movies, setMovies] = useState([]);
    
        useEffect(() => {
            const fetchMovies = async () => {
                if (mood) {
                    try {
                        const moviesData = await getMovie(mood);
                        console.log(moviesData);  // This logs the data correctly
                        setMovies(moviesData);
                    } catch (error) {
                        console.error("Error fetching movies:", error);
                    }
                }
            };
    
            fetchMovies();
        }, []);
    
        return (
            <div style={{ padding: "128px" }}>
                <h3>Movies</h3>
                <ul>
                    {movies.map((movie) => (
                        <li key={movie.id}>
                            <div>{movie.title}</div>
                            <div>{movie.genre}</div>
                        </li>
                    ))}
                </ul>
            </div>
        );
    };
    
    export default Movies;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search