Home > database >  React fetching data from only one object? Uncaught TypeError: Cannot read properties of null (readin
React fetching data from only one object? Uncaught TypeError: Cannot read properties of null (readin

Time:12-09

I am trying to map the data of this api endpoint. It doesn't have a object name like results or something like that. So, what should I use to map that data?

https://api.themoviedb.org/3/movie/10000?api_key=4f298a53e552283bee957836a529baec this is the endpoint that I am trying to use.

this is the state management part, don't mind fetch part btw, I did some arrangements somewhere else to set that movieId;

const [current, setCurrent] = useState([]);

const searchById = (movieId) => {
    fetch(API_SEARCH_BY_ID   movieId   API_KEY)
      .then((res) => res.json())
      .then((data) => {
        console.log(data);
        setCurrent(data); 
        console.log(current);
        successAlert();
      });
  };

This is the map function in my component file;

<Container fluid>
        {current.map((current, currentReq) => (
          <MovieDetails current={current} key={currentReq.id} {...currentReq}></MovieDetails>
        ))}
</Container>

This is the error I am getting;

Details.js:22 Uncaught TypeError: Cannot read properties of null (reading 'map')

I am still in the learning phase of react, so I need some help here. Probably I am missing something silly here.

Thanks to DanPhilipBejoy, Answer is: generating a empty array named test and pushing the data into that array.

const searchById = (movieId) => {
    fetch(API_SEARCH_BY_ID   movieId   API_KEY)
      .then((res) => res.json())
      .then((data) => {
        console.log(data);
        const test = [data]
        setCurrent(test); 
        successAlert();
      });
  };

CodePudding user response:

You don't need a loop if its just one element.

<Container fluid>
      <MovieDetails current={current} .../>
</Container>

OR

In case if you want to retain the JSX structure just do

setCurrent([data]); 

CodePudding user response:

Your endpoint's response is an object not an array, you can't map an object!

  • Related