fetching data in getStaticProps
Unanswered
Chausie posted this in #help-forum
ChausieOP
hey guys i try to fetch data in getStaticProps but the api url throws error:
it works fine in normal components
it works fine in normal components
import { useEffect, useState } from "react";
import useSWR from "swr";
export default function LastSalesPage(props) {
const [sales, setSales] = useState(props.sales);
// const [isLoading, setIsLoading] = useState(false);
const { data, error } = useSWR(
"https://nextjs-course-46616-default-rtdb.europe-west1.firebasedatabase.app/sales.json",
(url) => fetch(url).then((res) => res.json())
);
useEffect(() => {
if (data) {
const transformedSales = [];
for (const key in data) {
transformedSales.push({
id: key,
username: data[key].username,
volume: data[key].volume,
});
}
setSales(transformedSales);
}
}, [data]);
if (error) {
return <p>Failed to load.</p>;
}
if (!data || !sales) {
return <p>Loading...</p>;
}
return (
<ul>
{sales.map((sale) => (
<li key={sale.id}>
{sale.username} - ${sale.volume}
</li>
))}
</ul>
);
}
export async function getStaticProps(context) {
const response = await fetch(
"https://nextjs-course-46616-default-rtdb.europe-west1.firebasedatabase.app/sales.json"
);
const data = await response.json();
const transformedSales = [];
console.log(transformedSales);
for (const key in data) {
transformedSales.push({
id: key,
username: data[key].username,
volume: data[key].volume,
});
}
return { props: { sales: transformedSales } };
}67 Replies
Peterbald
Please try to put the error handling in getStaticProps function.
export async function getStaticProps(context) {
try {
const response = await fetch(
"https://nextjs-course-46616-default-rtdb.europe-west1.firebasedatabase.app/sales.json"
);
if (!response.ok) {
throw new Error('Failed to fetch');
}
const data = await response.json();
const transformedSales = [];
for (const key in data) {
transformedSales.push({
id: key,
username: data[key].username,
volume: data[key].volume,
});
}
return { props: { sales: transformedSales } };
} catch (error) {
console.error('Error fetching data:', error);
return { props: { sales: [] } }; // Return empty array in case of error
}
export async function getStaticProps(context) {
try {
const response = await fetch(
"https://nextjs-course-46616-default-rtdb.europe-west1.firebasedatabase.app/sales.json"
);
if (!response.ok) {
throw new Error('Failed to fetch');
}
const data = await response.json();
const transformedSales = [];
for (const key in data) {
transformedSales.push({
id: key,
username: data[key].username,
volume: data[key].volume,
});
}
return { props: { sales: transformedSales } };
} catch (error) {
console.error('Error fetching data:', error);
return { props: { sales: [] } }; // Return empty array in case of error
}
This is the code I can provide
@Peterbald Please try to put the error handling in getStaticProps function.
export async function getStaticProps(context) {
try {
const response = await fetch(
"https://nextjs-course-46616-default-rtdb.europe-west1.firebasedatabase.app/sales.json"
);
if (!response.ok) {
throw new Error('Failed to fetch');
}
const data = await response.json();
const transformedSales = [];
for (const key in data) {
transformedSales.push({
id: key,
username: data[key].username,
volume: data[key].volume,
});
}
return { props: { sales: transformedSales } };
} catch (error) {
console.error('Error fetching data:', error);
return { props: { sales: [] } }; // Return empty array in case of error
}
ChausieOP
I have done these but it just sends empty array on gives the error back
Peterbald
Can you show me the error?
@Peterbald Can you show me the error?
ChausieOP
Error fetching data: TypeError: fetch failed
at Object.fetch (node:internal/deps/undici/undici:11730:11)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async getStaticProps (webpack-internal:///./pages/last-sales.js:95:26) {
cause: Error: Client network socket disconnected before secure TLS connection was established
at connResetException (node:internal/errors:787:14)
at TLSSocket.onConnectEnd (node:_tls_wrap:1727:19)
at TLSSocket.emit (node:events:526:35)
at endReadableNT (node:internal/streams/readable:1589:12)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
code: 'ECONNRESET',
path: undefined,
host: 'nextjs-course-46616-default-rtdb.europe-west1.firebasedatabase.app',
port: 443,
localAddress: null
}
}Peterbald
The url is valid?
Please try to make the simple Node.js Script for testing URL
const fetch = require('node-fetch');
fetch('https://nextjs-course-46616-default-rtdb.europe-west1.firebasedatabase.app/sales.json')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error fetching data:', error));
fetch('https://nextjs-course-46616-default-rtdb.europe-west1.firebasedatabase.app/sales.json')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error fetching data:', error));
This is the script
@Peterbald The url is valid?
ChausieOP
yes i have tried it in normal functions it works but not with getStaticProps
Peterbald
getStaticProps is working on the other Components?
ChausieOP
No the fetching method doesn't work with async function getStaticProps only but it works without any issues in normal components
Peterbald
export const getStaticProps = (async (context) {
try {
const response = await fetch(
"https://nextjs-course-46616-default-rtdb.europe-west1.firebasedatabase.app/sales.json"
);
if (!response.ok) {
throw new Error('Failed to fetch');
}
const data = await response.json();
const transformedSales = [];
for (const key in data) {
transformedSales.push({
id: key,
username: data[key].username,
volume: data[key].volume,
});
}
return { props: { sales: transformedSales } };
} catch (error) {
console.error('Error fetching data:', error);
return { props: { sales: [] } }; // Return empty array in case of error
})
try {
const response = await fetch(
"https://nextjs-course-46616-default-rtdb.europe-west1.firebasedatabase.app/sales.json"
);
if (!response.ok) {
throw new Error('Failed to fetch');
}
const data = await response.json();
const transformedSales = [];
for (const key in data) {
transformedSales.push({
id: key,
username: data[key].username,
volume: data[key].volume,
});
}
return { props: { sales: transformedSales } };
} catch (error) {
console.error('Error fetching data:', error);
return { props: { sales: [] } }; // Return empty array in case of error
})
Please try to make the function like this
@Peterbald export const getStaticProps = (async (context) {
try {
const response = await fetch(
"https://nextjs-course-46616-default-rtdb.europe-west1.firebasedatabase.app/sales.json"
);
if (!response.ok) {
throw new Error('Failed to fetch');
}
const data = await response.json();
const transformedSales = [];
for (const key in data) {
transformedSales.push({
id: key,
username: data[key].username,
volume: data[key].volume,
});
}
return { props: { sales: transformedSales } };
} catch (error) {
console.error('Error fetching data:', error);
return { props: { sales: [] } }; // Return empty array in case of error
})
ChausieOP
Error fetching data: TypeError: fetch failed
at Object.fetch (node:internal/deps/undici/undici:11730:11)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async getStaticProps (webpack-internal:///./pages/last-sales.js:95:26) {
cause: Error: read ECONNRESET
at TLSWrap.onStreamRead (node:internal/stream_base_commons:217:20) {
errno: -4077,
code: 'ECONNRESET',
syscall: 'read'
}
}
Error fetching data: TypeError: fetch failed
at Object.fetch (node:internal/deps/undici/undici:11730:11)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async getStaticProps (webpack-internal:///./pages/last-sales.js:95:26) {
cause: Error: read ECONNRESET
at TLSWrap.onStreamRead (node:internal/stream_base_commons:217:20) {
errno: -4077,
code: 'ECONNRESET',
syscall: 'read'
}
}Peterbald
remove .next folder and re-run the server and refresh your browser.
very weird
@Peterbald remove .next folder and re-run the server and refresh your browser.
ChausieOP
it gave the same error again
Peterbald
try to remove context in getStaticProps function parameter
ChausieOP
Didn't change here is the photo from browser
Peterbald
Can you provide the whole code?
ChausieOP
I have provided it in the beginning
@Chausie I have provided it in the beginning
what version of next and nodejs are you using?
I tried with your link without an issue
ChausieOP
Next js 13.0.7 and node 20
let me see if I can get next13.0.7
@Ray can you try with different node version?
ChausieOP
Are u testing it in export async function getStaticProps () {...}?
sure
@Ray sure
ChausieOP
I'm using nodejs 20.10.0
have you try on different browser?
@Ray have you try on different browser?
ChausieOP
Try it exactly like my code the url works fine
@Ray Click to see attachment
ChausieOP
Can u send me the code u use
just tried your code
and it works
can you try create a new project and test the code?
it should be something wrong on your device
@Ray it should be something wrong on your device
ChausieOP
Error fetching data: TypeError: fetch failed
at Object.fetch (node:internal/deps/undici/undici:11730:11)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async getStaticProps (webpack-internal:///./pages/last-sales.js:95:26) {
cause: Error: Client network socket disconnected before secure TLS connection was established
at connResetException (node:internal/errors:787:14)
at TLSSocket.onConnectEnd (node:_tls_wrap:1727:19)
at TLSSocket.emit (node:events:526:35)
at endReadableNT (node:internal/streams/readable:1589:12)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
code: 'ECONNRESET',
path: undefined,
host: 'nextjs-course-46616-default-rtdb.europe-west1.firebasedatabase.app',
port: 443,
localAddress: null
}
}
at Object.fetch (node:internal/deps/undici/undici:11730:11)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async getStaticProps (webpack-internal:///./pages/last-sales.js:95:26) {
cause: Error: Client network socket disconnected before secure TLS connection was established
at connResetException (node:internal/errors:787:14)
at TLSSocket.onConnectEnd (node:_tls_wrap:1727:19)
at TLSSocket.emit (node:events:526:35)
at endReadableNT (node:internal/streams/readable:1589:12)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
code: 'ECONNRESET',
path: undefined,
host: 'nextjs-course-46616-default-rtdb.europe-west1.firebasedatabase.app',
port: 443,
localAddress: null
}
}
@Ray same with new project?
ChausieOP
Yes, I'm trying to reinstall node.js to v20.7.0
it still work for me with v20.10.0
can you try this link in getStaticProps?
https://jsonplaceholder.typicode.com/posts
https://jsonplaceholder.typicode.com/posts
and what os are you using?
@Ray and what os are you using?
ChausieOP
Windows 11
@Ray does this link work?
ChausieOP
yes it did why it didn't work with the firebase api url?
firebase api require tls 1.2
ChausieOP
what is it?
you can open the link with browser right?
are you using wsl?
ChausieOP
i dont know
@Ray you can open the link with browser right?
ChausieOP
yep
@Ray are you using wsl?
ChausieOP
How can i fix it?
windows subsystem for linux
or are you developing it natively on windows?
@Ray or are you developing it natively on windows?
ChausieOP
natively on windows 11
hmm
not work with latest version of nextjs right?
ChausieOP
yes i think its the same with latest version to
ah no idea, you may want to ask firebase support
tell them you got
Client network socket disconnected before secure TLS connection was established@Ray tell them you got ` Client network socket disconnected before secure TLS connection was established`
ChausieOP
Oh, ok thank you for your help
does the data come from firestore or real time database? could you try it with their sdk?