0

I am doing a React.js project. I am fetching data from an API and pass it from the parent component by props. Also, I am using different endpoints of the same API in this children component. I need to match the "characters/people" from the props, with the ones inside this new endpoint of the same API. I have a function that it seems to work, but I get two errors. The first one is not always, but sometimes in the console it shows error 429 too many API calls. I did a setTimeOut function that it seems it solved. But, now I have another error from the catch that says: TypeError: fetch(...).json is not a function. This is the code:

import styles from './MovieDetail.module.css';

const MovieDetail = ({ film }) => {

    const peoples = film.properties?.characters.map(async (characterURL) => {
        try {
            const people = await fetch(characterURL).json().results;
            if (people.ok) {
                setTimeout(() => {
                    return people;
                }, 1000)
            };
        }
        catch (err) {
            console.error('Error peoples', err)
        }
    })
    console.log('peoples MovieDetail', peoples)

    return (
        <div className={styles.card}>
            <div className={styles.container}>
                <h2>{film.properties?.title}</h2>
                <p>{film.description}</p>
                <p>Release date: {film.properties?.release_date}</p>
                <p>Director: {film.properties?.director}</p>
                <p>Producer: {film.properties?.producer}</p>
                <p>Characters:</p>
                {peoples?.map(people=> (
                    <ul id={styles.list}>
                        <li>{people.properties?.name}</li>
                    </ul>
                ))}
            </div>            
        </div>
    );
}
 
export default MovieDetail;

This is the whole code in sandbox. Thanks in advance.

2 Answers 2

1

I've gone through your code, and there are few mistakes, that you're doing.

First is: You are passing your props named as films from your parent component and getting as film in your child component.

so change this in your ItemContainer/index.jsx

return <MovieDetail key={film?.properties?.episode_id} film={film} />;

and Second is: you need to await for your json as well:

so change this in your MovieDetail/Index.jsx

const peoples = film?.properties?.characters.map(async (characterURL) => {
  try {
    const response = await fetch(characterURL);
    const people = await response.json().results;
    if (response.ok) {
      setTimeout(() => {
        return people;
      }, 1000);
    }
  } catch (err) {
    console.error("Error peoples", err);
  }
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Pradip. I fixed the mistake and I also added the await for the json. However, it doesn't render the map of peoples in the jsx. The console.log(peoples) gives an array of promises undefined. This is the error in the console: [Prototype]]: Promise [[PromiseState]]: "fulfilled" [[PromiseResult]]: undefined
because, peoples return the Promise so you need to do, Promise.all([peoples]) and also you need to use useEffect and useState to fetch peoples and store their data in state. And map your data from state.
1

Try to await the json() call separately.
Also, add a state array to store the data to display and call the fetch function in a useEffect hook:

const [people, setPeople] = useState([]);

const getPeoples = () => {
  film.properties?.characters.map(async (characterURL) => {
    try {
      const response = await fetch(characterURL);
      const data = await response.json();
      if (data.results.ok) {
        // Add new people to `people` array
        setPeople((oldPeople) => [...oldPeople, ...data.results]);
      }
    } catch (err) {
      console.error('Error peoples', err);
    }
  });
};

useEffect(() => {
  getPeoples();
}, [film]);

2 Comments

Thanks Luca. I called the await separately, but I still having issues. The map in the jsx ddoesn't render anything. I did a console.log(peoples) and it gives me an array of promises undefined. This is the error: [Prototype]]: Promise [[PromiseState]]: "fulfilled" [[PromiseResult]]: undefined
@JoaquinPalacios Try with the edited answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.