Dauke bayanai daga APIs a cikin Next.js: Amfani da getStaticProps da samunServerSideProps

A cikin aiwatar da haɓaka Next.js aikace-aikacen, tattara bayanai daga APIs muhimmin al'amari ne don nuna abun ciki mai ƙarfi. Wannan labarin zai jagorance ku ta hanyar amfani da shi getStaticProps don ƙwanƙwasa bayanai a lokacin aikin ginin da kuma amfani da su getServerSideProps don debo bayanai daga APIs akan kowace buƙata.

Amfani da getStaticProps

getStaticProps ginanniyar hanya ce a cikin Next.js wacce ke goyan bayan ɗauko bayanan a tsaye yayin aikin ginin. Yana ba ku damar ƙirƙirar shafuka masu mahimmanci tare da bayanan da aka tambaya, waɗanda aka riga aka yi kafin a tura aikace-aikacen. Ga babban misali na amfani getStaticProps:

export async function getStaticProps() {  
  const response = await fetch('https://api.example.com/data');  
  const data = await response.json();  
  
  return {  
    props: {  
      data,  
    },  
  };  
}  

A cikin misalin da ke sama, muna amfani fetch da neman bayanai daga API kuma mu dawo da bayanan azaman abin dogaro.

Amfani da getServerSideProps

getServerSideProps wata hanya ce Next.js da ke ba ku damar debo bayanai daga APIs akan kowace buƙata. Wannan yana tabbatar da cewa abun ciki koyaushe yana sabuntawa kuma yana da ƙarfi. Ga misalin amfani getServerSideProps:

export async function getServerSideProps() {  
  const response = await fetch('https://api.example.com/data');  
  const data = await response.json();  
  
  return {  
    props: {  
      data,  
    },  
  };  
}  

Hanyar getServerSideProps za ta nemi bayanai daga API duk lokacin da aka yi buƙatu zuwa shafin.

Kammalawa

A cikin wannan sashe, kun koyi yadda ake samun ingantaccen bayanai daga APIs a cikin Next.js aikace-aikacenku. Ta amfani getStaticProps da getServerSideProps, za ka iya nuna duka a tsaye da kuma abun ciki a sassauƙa a cikin aikace-aikacenka.