Home > Blockchain >  next.js getStaticProps Serialize issue
next.js getStaticProps Serialize issue

Time:02-03

I'm using next.js for a project where axios fetch in getStaticProps doesnot seem to work even though the URL is serialised in configuration.I tried serializing again by passing the response to JSON.parse but still cant find a solution.

import axios from "axios"; import Qs from "qs";

My axios config code below:


    const axiosTmdbApi = axios.create({
      baseURL: "https://api.themoviedb.org/3",
      headers: { "content-Type": "application/json/" },
      paramsSerializer: {
        serialize: (params) =>
          Qs.stringify({ ...params, api_key: apiKey }, { arrayFormat: "brackets" }),
      },
    });```


**My category which is passed as a parameter to invoke getTvList or getMovieList data below:**

import axiosTmdbApi from "./axiosTmdbApi";

export const category = {
  movie: "movie",
  tv: "tv",
};

export const type = {
  top_rated: "top_rated",
  popular: "popular",
};

const tmdbApi = {
  getTvList: (tvType, params) => {
    const url = "tv/"   type[tvType];
    return axiosTmdbApi.get(url, params);
  },
  getMovielist: (movieType, params) => {
    const url = "movie/"   type[movieType];
    return axiosTmdbApi.get(url, params);
  },
};

export default tmdbApi;```

Using getStaticProps to fetch my API

import tmdbApi from "../../api/tmdbApi"; import { type, category } from "../../api/tmdbApi";


    const Movies = ({ data }) => {
      console.log(data);
      return (
        <>
          <h1 className="bg-success">Movies</h1>
          
        </>
      );
    };
    
    export default Movies;

    export async function getStaticProps() {
      let params = {};
      let response;
    
      response = await tmdbApi.getMovielist(type.popular, {
        params,
      });
      const data = JSON.parse(JSON.stringify(response));
    
    
      return {
        props: { data },
      };
    }```

 
**Error :index.js?46cb:602 Uncaught TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'ClientRequest'
    |     property 'socket' -> object with constructor 'TLSSocket'
    --- property '_httpMessage' closes the circle **


CodePudding user response:

Try adding console.log and see what values are being handled at each stage. Instead of const data = JSON.parse(JSON.stringify(response)), you should be doing const data = response.data.

and change return statement to

  return {
    props: { data: data || [] },
  }; 
  • Related