I am using nextjs to build a directory. I effectively want to click on 'more info' and an info page to load under the URL of /info/[id]-[first_name]-[last_name].
I am pulling data from an api by id, which will then get the first_name and last_name data.
I have a file inside an info folder named [id]-[first_name]-[last_name] :
export default function Info({ info }) {
return (
<div>
<h1>First Name</h1>
<p> Last Name </p>
</div>
);
}
export const getStaticPaths = async () => {
const res = await fetch('http://xxx:1337/api/info');
const data = await res.json();
// map data to an array of path objects with params (id)
const paths = [data].map(info => {
return {
params: [{
id: `${info.id}-`,
first_name: `${info.first_name}-`,
last_name: `${info.last_name}`
}]
}
})
return {
paths,
fallback: false
}
}
export const getStaticProps = async (context) => {
const id = context.params.id;
const res = await fetch('http://xxxx:1337/api/info/' + id);
const data = await res.json();
return {
props: { info: data }
}
With this I just get the error:
Error: A required parameter (id]-[first_name]-[last_name) was not provided as a string in getStaticPaths for /info/[id]-[first_name]-[last_name]
I guess that error is pretty self-explanatory, but I am blocked at this point. I have seen that i may be able to use a slug, but that means re-working a lot of the api.
Any direction with this is apprecated. Thanks!
in this way you can catch all attributes /info/[id]/[first_name]/[last_name]
by making the file /info/[...slug]
export const getStaticProps = async ({ query }) => {
const [id ,firstname ,lastname] = query.slug }
or keep it /info/[slug] and get it as string after that you can split it
Related
I'm using nextjs 13, just started. I'm using getServerSideProps() but the request is rethrown every time it comes to the page. I want to check my Store field first, if the store field is empty, then it should send a request. how can I do it.
// current
export const getServerSideProps = async () => {
const { data } = await axios.get(`https://www.freetogame.com/api/games`);
return { props: { data: data } };
};
// i want
export const getServerSideProps = async () => {
if(store.gamesState.length <0 ){
const { data } = await axios.get(`https://www.freetogame.com/api/games`);
dispatch(gamesActions.setGames(data))
}
};
I am fetching all posts from the backend from the API call http://localhost:3000/api/jobs and it is working perfectly by using getstaticProps(). Now I want to get a particular post based on slug and my API call is http://localhost:3000/api/jobs/:slug and it perfectly working API call But whenever I used the code shown below for dynamic routes it shows me a server error on the frontend and unable to fetch particular post data.
[slug].js
export const getStaticPaths = async () => {
const res = await fetch(`${API}/jobs`);
const post = await res.json();
const paths = post.map(job => {
return {
params: { slug: job.slug }
}
})
return {
paths,
fallback:true
}
}
export const getStaticProps = async (ctx) => {
const slug = ctx.params.slug;
const [job, photo] = await Promise.all([
fetch(`${API}/jobs/${slug}`).then(r => r.json()),
`${API}/jobs/photo/${slug}`
]);
if (!job) {
return {
notFound:true
}
}
return {
props: {
job,
photo
},
revalidate:60
}
}
Also whenever I used another API call like http://localhost:3000/api/jobs-edit which has the same function as that of http://localhost:3000/api/jobs inside getStaticPaths() then it performs well and gives us single post data.
What can be the problem?
I have a Next page that uses next-i18next in a getServerSideProps and I have another page that uses getServerSideProps to pull data from MongoDB. Both work correctly.
I would like to be able to add next-i18next to the function that connects to Mongo (basically combine the getServerSideProps functions), but I'm getting the error:
nexti18n-next Error: Initial locale argument was not passed into serverSideTranslations'
The first page's getServerSideProps function that connects to next-i18n
export const getServerSideProps = withAuthUserSSR({ whenUnauthed: AuthAction.REDIRECT_TO_LOGIN,})(async ({ locale, }) => {
return {
props: {
...(await serverSideTranslations(locale,
[
'language-file',
...
]
)),
},
};
})
The getServerSideProps function in the second page that pulls data from Mongo:
export const getServerSideProps = withAuthUserSSR({ whenUnauthed: AuthAction.REDIRECT_TO_LOGIN })(async (context) => {
const username = context.params.var[0];
const userId = context.params.var[2];
const { db } = await connectToDatabase();
const pipeline = [
...
]
const postdata = await db.collection('posts').aggregate(pipeline).toArray();
return {
props: {
userId,
username,
postdata: JSON.parse(JSON.stringify(postdata)),
},
};
})
Is it possible to 'add' the next-i18next code to the second function? It seems to me to be an issue with the different way 'locale' and 'context' are defined in each function. I have tried lots of combinations of both but end up messing up either the mongo query or the translations.
This is how I thought it would be done:
export const getServerSideProps = withAuthUserSSR({ whenUnauthed: AuthAction.REDIRECT_TO_LOGIN })(async (context,{ locale, }) => {
const username = context.params.var[0];
const userId = context.params.var[2];
const { db } = await connectToDatabase();
const pipeline = [
...
]
const postdata = await db.collection('posts').aggregate(pipeline).toArray();
return {
props: {
...(await serverSideTranslations(locale,
[
'language-files',
...
]
)),
userId,
username,
postdata: JSON.parse(JSON.stringify(postdata)),
},
};
})
Many thanks for any possible help!
The Issue
I cannot query the API by slug, it must be by id. An KeystoneJS headless CMS provide the data via API and my NextJS should use this data in a static generated Next.js app.
Keystone API must be queried like this:
All Posts: (ALL_POSTS_QUERY)
query {
allPosts {
id
slug
title
}
}
Single Post: (POST_QUERY)
query {
Post(where: { id: $id }) {
title
body
}
}
I do use Apollo Client to connect to the API endpoint.
A query for an individual post must be formatted as described above, with an id variable and that's what seems to be the issue. I need to generate static pages by slug and not by id.
The functions
getStaticPaths()
export const getStaticPaths = async () => {
const { data } = await apolloClient.query({
query: ALL_POSTS_QUERY,
});
return {
paths: data.allPosts.map(({ id, slug }) => ({
params: { slug: slug },
})),
fallback: false,
};
};
getStaticProps()
export const getStaticProps = async ({ params }) => {
const id = params.id;
const { data } = await apolloClient.query({
query: POST_QUERY,
variables: {
id,
},
});
return {
props: {
term: data.Post,
},
};
};
More info about KeystoneJS generated APIs.
Please help
I'm very new to developing so my understanding of this is still basic. Apologies if I've misunderstood the logic. Please can anyone help me with where I'm going wrong with my functions? I wasn't able to find anyone else trying to build dynamic routes by slug but querying the API by id to retrieve that post's data.
Your problem is that you want to access the prop id of params, but params.id simply does not exist. What exists is params.slug. If you want to pass through the id, then change your code to this:
export const getStaticPaths = async () => {
const { data } = await apolloClient.query({
query: ALL_POSTS_QUERY,
});
return {
paths: data.allPosts.map(({ id, slug }) => ({
params: { id },
})),
fallback: false,
};
};
Now you are passing through the id instead of the slug and should be fine.
I'm trying to deploy an app using Prismic as CMS and everything works perfectly locally, but once I deploy to vercel I get the error:
19:09:51.850 | TypeError: Cannot read property 'titulo_categoria' of undefined
There seems to be something wrong when it tries to get the data from Prismic.
My code is the following:
import {getAllCategorias, getCategory2} from '../../lib/api';
export default function Index({cat}) {
return <>{cat.titulo_categoria[0].text}</>;
}
export async function getStaticProps({params}) {
const data = await getCategory2(params.slug);
return {
props: {
cat: data?.categorias ?? null,
},
};
}
export async function getStaticPaths() {
const allPosts = await getAllCategorias();
return {
paths: allPosts?.map(({node}) => `/test/${node._meta.uid}`) || [],
fallback: true,
};
}
And the API code that gets data from Prismic is:
import Prismic from 'prismic-javascript';
const REPOSITORY = process.env.PRISMIC_REPOSITORY_NAME;
const REF_API_URL = `https://${REPOSITORY}.prismic.io/api/v2`;
const GRAPHQL_API_URL = `https://${REPOSITORY}.prismic.io/graphql`;
// export const API_URL = 'https://your-repo-name.cdn.prismic.io/api/v2'
export const API_TOKEN = process.env.PRISMIC_API_TOKEN;
export const API_LOCALE = process.env.PRISMIC_REPOSITORY_LOCALE;
export const PrismicClient = Prismic.client(REF_API_URL, {
accessToken: API_TOKEN,
});
async function fetchAPI(query, {previewData, variables} = {}) {
const prismicAPI = await PrismicClient.getApi();
const res = await fetch(
`${GRAPHQL_API_URL}?query=${query}&variables=${JSON.stringify(variables)}`,
{
headers: {
'Prismic-Ref': previewData?.ref || prismicAPI.masterRef.ref,
'Content-Type': 'application/json',
'Accept-Language': API_LOCALE,
Authorization: `Token ${API_TOKEN}`,
},
}
);
if (res.status !== 200) {
console.log(await res.text());
throw new Error('Failed to fetch API');
}
const json = await res.json();
if (json.errors) {
console.error(json.errors);
throw new Error('Failed to fetch API');
}
return json.data;
}
export async function getCategory2(slug) {
const data = await fetchAPI(
`
query CategoryBySlug($slug: String!, $lang: String!) {
categorias(uid: $slug, lang: $lang) {
titulo_categoria
_meta {
uid
}
}
}
`,
{
variables: {
slug,
lang: API_LOCALE,
},
}
);
return data;
}
Any idea what's wrong with this? I been trying to figure it out for the whole day without any luck
Perhaps you already checked that, but since you mentioned everything works locally and not on Vercel are you sure your environment variables are set there? Especially PRISMIC_API_TOKEN since it appears you're relying on it to query the API?
Also I'm a bit worried about that part of the code:
props: {
cat: data?.categorias ?? null,
}
...where you might be sending a null value to your Index component resulting in your error, I'd try that instead:
props: {
cat: data?.categorias ?? {},
}
...plus using the safe navigation operator (?.) on the Index component?
Let me know how it goes!