TMDB and Next Js

113 Views Asked by At

I am trying to integrate the TMDB API into my next js application. I went ahead and logged in, picked up my API key and saved it into a .env file. I then used axios to make the request. No error seems to occur in the file so far until I import the file into another file which I want to use. The data I am getting back seems not to be an array as expected. Instead, next js is throwing an error:

Error: Cannot read properties of undefined (reading 'map').

{movies.map((movie) => ({movie.title}))}

Below is my full code:

tmdb.js

import axios from "axios";

const TMDB_API_KEY = process.env.TMDB_API_KEY
const TMDB_BASE_URL = 'https://api.themoviedb.org/3';

export const fetchMovies = async () => {
    try {
        const response = await axios.get(`${TMDB_BASE_URL}/movie/popular`, {
            params: {
                api_key: TMDB_API_KEY,
                language: 'en-US',
                page: 1,
            },
        });
        return response.data.results;
    } catch (error) {
        return [];
    }
}

moviesdisplaylist.jsx

import './moviesdisplaylist.css'
import {fetchMovies} from '../../../../api/tmdb';

export default function MoviesDisplayList({movies}) {
  return (
      <>
        <div>
          <h1>TMDB movies</h1>
          <ul>
            {movies.map((movie) => (
              <li key={movie.id}>{movie.title}</li>
            ))}`your text`
          </ul>
        </div>
      </>
  );
}

export async function getStaticProps() {
  const movies = await fetchMovies();
  return {
    props: {
      movies: [],
    }
  }
}

I have tried searching up online for examples or the way it is supposed to be done but seems like the documentation is very limited. Even the TMDB docs does not show how to integrate it with different frameworks. Any help will be appreciated.

1

There are 1 best solutions below

0
Emre On
export async function getServerSideProps() {
  const movies = await fetchMovies();
  return {
    props: {
      movies,
    }
  }
}

try this.