Home > Blockchain >  Fetching multipule endpoints at one return undefined
Fetching multipule endpoints at one return undefined

Time:07-30

import React, { useEffect, useState } from "react";
import { endpoint, apiKey } from "../api";
import Container from "../components/layouts/Container";

export default function Movie({ route }) {
  const { movieId } = route.params;
  const [movieDetails, setMovieDetails] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const urls = [
    `${endpoint}/movie/${movieId}?api_key=${apiKey}`,
    `${endpoint}/movie/${movieId}/credits?api_key=${apiKey}`,
    `${endpoint}/movie/${movieId}/images?api_key=${apiKey}`,
    `${endpoint}/movie/${movieId}/reviews?api_key=${apiKey}`,
    `${endpoint}/movie/${movieId}/similar?api_key=${apiKey}`,
  ];

  useEffect(() => {
    const fetchData = () => {
      setIsLoading(true);
      Promise.all(
        urls.map((url) => {
          return fetch(url);
        })
      )
        .then((response) => {
          return Promise.all(response.map((res) => res.json()));
        })
        .then((data) => {
          setMovieDetails(data);
          setIsLoading(false);
        })
        .catch((err) => {
          console.log(err);
        });
    };
    fetchData();
  }, []);

  console.log(movieDetails[0]);

Hello, I've encountered a problem tha that when i try to fetch the request above when i console.log() it it first returns undefined and then return the desired response.

CodePudding user response:

The response is expected as initially the state is undefined.

During the request also, till a response is unresolved, the process is suspended and the state stays undefined.

A simple solve will be to move the console.log(movieDetails[0]) into the last .then() body or you could write your own Promise resolution functions.

CodePudding user response:

can you please use "Promise.allsettled" and see what happens? and can you re-check if you are missing any "await" keyword?

  • Related