Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

174
Views
Consumir API en React

¿Cuáles son las buenas formas de consumir api en reaccionar? Estoy creando un archivo para manejar la API para obtener datos. Y consumo en otro archivo, pero eso hace que los datos de la API se vuelvan indefinidos antes de devolver lo real.

Película.js

 import { useState, useEffect } from 'react'; import axios from 'axios'; const apiKey = 'apikey'; const url = 'https://api.themoviedb.org/3'; const Movie = { GetMovieTrends() { const [movies, setMovies] = useState({}); useEffect(() => { axios.get(`${url}/trending/movie/day?api_key=${apiKey}`) .then((response) => { setMovies(response.data); }) .catch((err) => { console.log(err); }); }, []); return movies; }, GetMovieGenres() { const [genre, setGenre] = useState(null); useEffect(() => { axios.get(`${url}/genre/movie/list?api_key=${apiKey}`) .then((response) => { setGenre(response.data.genres); }) .catch((err) => console.log(err)); }, []); return genre; } }; export default Movie;

TrendContainer.jsx

 import React from "react"; import MovieImage from "./movie/MovieImage"; import MovieTextContainer from "./movie/MovieTextContainer"; import Movie from '../models/Movie.js'; import CircularProgress from '@material-ui/core/CircularProgress'; import { withStyles } from '@material-ui/core/styles'; const WaitForMovie = withStyles(() => ({ root: { color: '#212121', width: '64px !important', height: '64px !important', }, }))(CircularProgress); const TrendContainer = () => { const movieTrends = Movie.GetMovieTrends().results; return ( < div > < h1 className = 'heading1 bottom-margin' > Movie Trending < /h1> < div className = 'container-movie' > { movieTrends === undefined ? < WaitForMovie / > : movieTrends.slice(0, 7).map((movie) => { return ( < div className = 'wrap-card-movie bottom-margin' key = { movie.id } > < MovieImage url = { `https://image.tmdb.org/t/p/original/${movie.poster_path}` } name = { movie.title } /> < MovieTextContainer title = { movie.original_title } idGenre = { movie.genre_ids } /> < /div> ); }) } < /div> < /div> ); }; export default TrendContainer;
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Está violando las reglas de los ganchos en su componente de Movie , la forma en que está configurado actualmente nunca debería funcionar. El useState y useEfect siempre debe estar en el nivel superior de una función REACT, no solo una función JS.

Pero este podría ser un excelente ejemplo para usar un enlace personalizado en su aplicación...

 import { useState, useEffect } from 'react'; import axios from 'axios'; const API_KEY = 'apikey'; const API_URL = 'https://api.themoviedb.org/3'; const useMovies = ({apiKey = API_KEY, url = API_URL}) => { const [ movies, setMovies ] = useState(''); const [ genre, setGenre ] = useState(''); useEffect(() => { async function getMovieTrends(){ let movieData try{ movieData = axios.get(`${url}/trending/movie/day?api_key=${apiKey}`) } catch(error) { // don't keep this in production!!!! console.log(error); } setMovies(movieData.data); } async function getMovieGenres(){ let genreData try{ genreData = await axios.get(`${url}/genre/movie/list?api_key=${apiKey}`) } catch(error) { // don't keep this in production!!!! console.log(error) } setGenre(genreData?.data?.genres); } getMovieTrends(); getMovieGenres() }, [apiKey, url]); return {movies, genre} } export default useMovies;
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!