A cikin wannan sashe, za mu jagorance ku ta hanyar haɗa bayanan waje cikin Next.js aikace-aikacenku ta hanyar debo bayanai daga APIs RESTful ko GraphQL ayyuka. Ta hanyar haɗa APIs na waje, zaku iya wadatar da aikace-aikacenku tare da bayanan ainihin lokaci kuma ku samar da ƙwarewar mai amfani mai ƙarfi.
Dauke Bayanai daga API ɗin RESTful
APIs masu RESTful hanya ce gama gari don dawo da bayanai daga tushen waje. Ga yadda zaku iya debo bayanai daga API ɗin RESTful a cikin Next.js aikace-aikacenku:
Yi amfani da fetch
API ko ɗakin karatu kamar axios
yin buƙatun HTTP zuwa API na waje.
Karɓar amsa kuma sarrafa bayanan da aka samo daga API.
import axios from 'axios';
function fetchData() {
axios.get('https://api.example.com/data')
.then(response => {
const data = response.data;
// Process the data
})
.catch(error => {
console.error(error);
});
}
Dauke bayanai daga GraphQL Sabis
GraphQL yaren tambaya ne don APIs wanda ke ba ku damar buƙatar ainihin bayanan da kuke buƙata. Don debo bayanai daga GraphQL sabis a cikin aikace-aikacen ku Next.js:
Yi amfani da GraphQL ɗakin karatu na abokin ciniki kamar apollo-client
aika GraphQL tambayoyi zuwa sabis ɗin.
Ƙayyade GraphQL tambayar don tantance bayanan da kuke son ɗaukowa.
import { ApolloClient, InMemoryCache, gql } from '@apollo/client';
const client = new ApolloClient({
uri: 'https://graphql.example.com',
cache: new InMemoryCache(),
});
function fetchGraphQLData() {
client.query({
query: gql`
query {
posts {
title
content
}
}
`,
})
.then(result => {
const data = result.data;
// Process the data
})
.catch(error => {
console.error(error);
});
}
Kammalawa
Haɗa APIs na waje, ko RESTful ko GraphQL, yana ba ku damar samun damar bayanai daga tushe daban-daban da haɓaka Next.js aikace-aikacenku tare da sabuntawa da abun ciki mai ƙarfi. Ta ƙwarewar haɗin API, zaku iya samar da mafi arha kuma mafi jan hankalin mai amfani a aikace-aikacenku.