Home > database >  How to access data in an array in order to call an API?
How to access data in an array in order to call an API?

Time:10-06

I need to access a data inside an array from the response of the API (inside the result), because i need the ID value there to call another API. What could possibly wrong in my code that it shows an error?

Here is the object from the response of the API.

data: {page: 1, results: Array(7), total_pages: 1, total_results: 7}
headers: {cache-control: 'max-age=0, private, must-revalidate', content-type: 'application/json;charset=utf-8', etag: 'W/"6e36062c2e4d1dd119fceb30d730158c"'}
request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
status: 200
statusText: ""
[[Prototype]]: Object
import axios from "axios";
import React, { useEffect, useState } from "react";
import { API_KEY } from "./Constants";

const MovieList = () => {
  //   const [data, setData] = useState();
  useEffect(() => {
    axios({
      method: "get",
      url: `https://api.themoviedb.org/3/account/{account_id}/lists?api_key=${API_KEY}&session_id=${localStorage.getItem(
        "sessionID"
      )}`,
    })
      .then((response) => {
         setData(response.data.results);
         const myData = data.map((results, index) => ({
           id: results.id,
         }));
         );
         axios({
           method: "get",
           url: `https://api.themoviedb.org/3/list/${myData}?api_key=${API_KEY}`,
         })
           .then((response) => {
             console.log(response);
           })
           .catch((error) => {
             console.error(error);
           });
      })
      .catch((error) => {
        console.error(error);
      });
  }, []);
  return (
    <></>
  );
};

export default MovieList;

CodePudding user response:

You're initializing data with no value, making it undefined when the component mounts.

const [data, setData] = useState();

Then you're trying to map over data after setData(response.data.results). The problem is that setData is asynchronous, meaning when data.map is called, data will still likely be undefined

setData(response.data.results);
const myData = data.map((results, index) => ({
  id: results.id
}));

To solve this, change:

setData(response.data.results);
const myData = data.map((results, index) => ({
  id: results.id,
}));

to:

const { results } = response.data;
setData(results);
const myData = results.map(r => ({ id: r.id }));

By doing this, you're directly using the data from the API response, which should always be defined if the response was successful.

Note: You should also initialize data with an empty array, like so:

const [data, setData] = useState([]);

This guarantees that you can always do data.map in your component without error.

  • Related