TypeError: Failed to fetch next js - next.js

When trying to get data in next js, the server does not return anything at all, the console is empty, tell me, please, what could be wrong?
export const getStaticProps = async () => {
const res = await fetch('https://api.jikan.moe/v4/top/manga');
const data = await res.json();
console.log('data >>>', data);
return {
props: {
manga: data,
},
};
};

Related

getstaticprops returns data as undefined but in postman it's working?

// get data from server using getstatic props
export async function getStaticProps() {
const res = await axios.get("https://pharmaadmin.touchmediaads.com/api/dossier-formats")
console.log(res)
const data = res.data
console.log(data)
return {
props: {
data
},
}
}
What's the problem here??

How do I set a loading state when i'm fetching data outside a page function in next 13?

From the docs, this is how you fetch data, but since it's outside the function, how do I track the loading state so users can know when a data section is loading.
async function getData() {
const res = await fetch('https://api.example.com/...');
if (!res.ok) {
throw new Error('Failed to fetch data');
}
return res.json();
}
export default async function Page() {
const data = await getData();
return <main></main>;
}
You can use custom hooks for that:
useData.js
async function useData() {
const [loading, setLoading] = useState(true)
cost [error, setError] = useState(false)
const [data, setData] = useState()
useEffect(() => {
const fetchData = async () => {
setLoading(true)
const res = await fetch('https://api.example.com/...');
if (!res.ok) {
setError(true)
return
}
setError(false)
setLoading(false)
setData(res.json())
}
fetchData()
}, [])
return {loading, error, data}
}
//page
export default function Page() {
const {data, loading, error} = useData();
if(loading){ return <p>Loading...</p>}
if(error){ return <p>Error...</p>}
if(!data){ return <p>No data!!!</p>}
return <main></main>;
}
Later, you can set up your hook to use an uri param so you can reuse this hook in multiple pages.

How to fix undefined` cannot be serialized as JSON. Please use `null` or omit this value using getStaticprops

i am trying to fetch some data from an api using getStaticProps with next js. It returns the error undefinedcannot be serialized as JSON. Please usenull` or omit this value.
I have amended the code based on the solutions proposed online about the topic but none of them work.
export async function getStaticProps() {
const propertyForSale = await fetchApi(`${baseUrl}/properties/list?locationExternalIDs=5002&purpose=for-sale&hitsPerPage=6`);
const propertyForRent = await fetchApi(`${baseUrl}/properties/list?locationExternalIDs=5002&purpose=for-rent&hitsPerPage=6`);
return {
props: {
// Initial code
propertyForSale: propertyForSale?.hits,
propertyForRent: propertyForRent?.hits,
// the below snippet fixes the issue but return null
// propertyForSale: propertyForSale?.hits ?? null,
//propertyForRent: propertyForRent?.hits ?? null,
//the below snippet fixes the issue but return Unexpected token u in JSON at position 0
// propertyForSale: JSON.stringify(JSON.parse(propertyForSale?.hits))
//propertyForRent: JSON.stringify(JSON.parse(propertyForRent?.hits)),
}
}
}
fetchapi.js
export const baseUrl = 'https://bayut.p.rapidapi.com'
export const fetchApi = async (url) => {
const {result} = await axios.get((url), {
headers: {
'x-rapidapi-host': 'bayut.p.rapidapi.com',
'x-rapidapi-key': process.env.NEXT_PUBLIC_BAYU_API
},
});
console.log(result);
return result;
};
As Lazar pointed out in his comment, in your question's code snippet, you're trying to destructure a property that doesn't exist. And since axios returns an object with the data property, you're only left with destructuring the correct property:
const { data } = await axios.get(.....)
or...
const result = await axios.get(.....);
return result.data;
if you insist on the result thing :D
To fix the error I renamed constant result to data as per below.
I am not sure of what is the reason of this bug, if someone wanna add something to explain the reason why naming the constant data fixed the bug be my guess.
export const fetchApi = async (url) => {
const {data} = await axios.get((url), {
headers: {
'x-rapidapi-host': 'bayut.p.rapidapi.com',
'x-rapidapi-key': process.env.NEXT_PUBLIC_BAYU_API
},
});
return data;
};
export async function getStaticProps() {
const propertyForSale = await fetchApi(`${baseUrl}/properties/list?locationExternalIDs=5002&purpose=for-sale&hitsPerPage=6`);
const propertyForRent = await fetchApi(`${baseUrl}/properties/list?locationExternalIDs=5002&purpose=for-rent&hitsPerPage=6`);
return {
props: {
// Initial code
propertyForSale: propertyForSale?.hits,
propertyForRent: propertyForRent?.hits,
}
}
}
can you try this please?
return {
props: {
propertyForSale: propertyForSale?.hits || null,
propertyForRent: propertyForRent?.hits || null,
}
}

How to display 404 error page with react-query in next-ssr

I am using react query as stated in the doc
But, I am not sure how to return {notFound: true} from getServerSideProps. Could anyone help me how to handle this?
My code ins getServerSideProps is:
const queryClient = new QueryClient();
await queryClient.prefetchQuery('amenities', () => getAmenities(params?.id as string));
return {
props: {
dehydratedState: dehydrate(queryClient),
},
};
Now, what I want to do is, if the response is 404, then return 404 from getServerSideProps.
Update: I was not able to find any solution so removed react query in getServerSideProps. Now I'm fetching the data normally.
what you can do is do it on the client side.
const { data, isLoading, isError } = useQuery(
["amenities", router.query.id],
() => getAmenities(router.query.id)
)
if(isError) router.push('404');
You can do it in the server side too
const queryClient = new QueryClient();
const data = await queryClient.prefetchQuery('amenities', () => getAmenities(params?.id as string));
if (!data) {
return {
notFound: true,
}
}
return {
props: {
dehydratedState: dehydrate(queryClient),
},
};

App working locally but not on production: TypeError: Cannot read property 'titulo_categoria' of undefined

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!

Resources