Home > Mobile >  how can i give type in getServerSideProps of Nextjs with typescript?
how can i give type in getServerSideProps of Nextjs with typescript?

Time:10-14

I'm using NextJs typescript to make a little clone project. but, i got a problem with type in getServerSideProps. As you can see, in getServerSideProps, i am fetching data using with context.query. but, some error message is not fixed and i don't understand why that error appears. the error message is this. enter image description here

Type 'string[]' cannot be used as an index type.ts(2538)
Type 'undefined' cannot be used as an index type.ts(2538)
const genre: string | string[] | undefined

how can i fix this type problem??


import Head from "next/head";
import Nav from "../components/Nav/Nav";

import Header from "../components/Header/Header";
import Results from "../components/Results/Results";
import requests from "../utils/requests";

import { GetServerSideProps } from "next";

type HomeProps = {
  results: {}[];
};

export default function Home({ results }: HomeProps) {
  console.log(results);

  return (
    <div>
      <Results results={results} />
    </div>
  );
}

export const getServerSideProps: GetServerSideProps = async (context) => {
  const genre = context.query.genre 

  const response = await fetch(
    `https://api.themoviedb.org/3${
      requests[genre]?.url {/*this is problem line*/}  
   || requests.fetchTopRated.url
    }`
  );

  const data = await response.json();

  return {
    props: { results: data.results },
  };
};

CodePudding user response:

When you receive params via context, the value could be either string or string[] (or undefined) so you need to cast. It could be a single genre or multiple genres in the URL.

?genre=film or ?genre=film&genre=music

For you case, simply cast as string:

const genre = context.query.genre as string;

CodePudding user response:

Since the type of genre can be string or string[] (or undefined), it can not be used to index requests without being narrowed down to string via the use of an if statement:

if (typeof genre === 'string') {
  // Typescript now knows it is a string
  const response = await fetch(
    `https://api.themoviedb.org/3${
      requests[genre]?.fetchTopRated.url {/*this is problem line*/}  
   || requests.fetchTopRated.url
    }`
  );

  const data = await response.json();

  return {
    props: { results: data.results },
  };
} else if (typeof genre == 'object'){
   // handle case where it is an array
} else {
  // genre is undefined
}
  • Related