How can I solve a "fetch failed" when I reload a +page.svelte that depends on data from a +page.js - sveltekit

I get an fetch-failed error when I reload a +page.svelte (or load it via window.location.replace()) that depends on data from a +page.js.
In my current "solution" I use invalidate() in the onMount-function of the +error.svelte to load the data.
I'm looking for a better/correct approach to handle the loading.
error-message
fetch failed
TypeError: fetch failed
at Object.processResponse (C:xxx\node_modules\undici\lib\fetch\index.js:199:23)
at C:xxx\node_modules\undici\lib\fetch\index.js:928:38
at node:internal/process/task_queues:141:7
at AsyncResource.runInAsyncScope (node:async_hooks:202:9)
at AsyncResource.runMicrotask (node:internal/process/task_queues:138:8)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
+page.js
export const ssr = false; //1 module can't handle SSR
export const load = async ({ fetch }) => {
const response = await fetch(`https://localhost:5001/api/xxx`);
const obj= await response.json();
return {obj}
+error.svelte
onMount(async () => {
await invalidate();
});

Related

image is not loading and being blocked by CORB

I am getting a data with an image link and I want to show those images by using the link in my img tag. I have disabled CORS on my chrome and I am receiving the data successfully but when I try to render the image it gives me an error "Cross-Origin Read Blocking (CORB) blocked cross-origin response https://commons.wikimedia.org/wiki/File:A_Conversation_With_Oscar_Wilde_-_London_-_240404.jpg with MIME type text/html. See https://www.chromestatus.com/feature/5629709824032768 for more details"
Can you please help on how can I bypass this. I am using axios for to make the fetch request and React to render the image.
async function getData(location) {
try {
// Make API call to get coordinates of location
const geonameResponse = await axios.get(`https://api.opentripmap.com/0.1/en/places/geoname?name=${location}&apikey=${API_KEY}`)
//console.log(geonameResponse)
// Make API call to get features within 1000 meter radius of location
const radiusResponse = await axios.get(
`https://api.opentripmap.com/0.1/en/places/radius?radius=1000&lon=${geonameResponse.data.lon}&lat=${geonameResponse.data.lat}&limit=10&apikey=${API_KEY}`)
//console.log(radiusResponse)
// Make API call for each feature to get more detailed information
// Make API call for each feature to get more detailed information
const xidResponses = await Promise.all(
radiusResponse.data.features.map(async (item) => {
return new Promise((resolve) => {
setTimeout(async () => {
resolve(await axios.get(
`https://api.opentripmap.com/0.1/en/places/xid/${item.properties.xid}?apikey=${API_KEY}`
));
}, 2000);
});
})
);
// Set data to array of xidResponses
setData(xidResponses);
} catch (error) {
console.error(error);
}
}

Firestore error within React: Uncaught (in promise) TypeError: Cannot read properties of null (reading 'uid')

The following is my function in which I am trying to filter notes from my Firestore collection by user.uid:
const fetchPost = async () => {
const queryConstraints = []
if (user.uid != null) queryConstraints.push(where('userID', '==', user.uid))
if (user.email != null) queryConstraints.push(where('userEmail', '==',
user.email))
const q = query(collection(db, 'notes'), ...queryConstraints)
await getDocs(collection(q))
.then((querySnapshot)=>{
const newData = querySnapshot.docs
.map((doc) => ({...doc.data(), id:doc.id }));
setNotes(newData);
console.log(notes, newData);
})
}
Yet, when I try and run this code in the browser, regardless if it is Chrome, Safari, Firefox, I am getting the following error:
Uncaught (in promise) TypeError: Cannot read properties of null
(reading 'uid')
at fetchPost (NoteList.js:66:1)
I am not sure how to fix this error, or really the right question to ask over how ask over why this this is happening.
Previously, I was using the following function:
const fetchPost = async () => {
await getDocs(collection(db, "notes"))
.where('userEmail', '==', user.email)
.then((querySnapshot)=>{
const newData = querySnapshot.docs
.map((doc) => ({...doc.data(), id:doc.id }));
setNotes(newData);
console.log(notes, newData);
})
}
I was getting the same error previously stated, but at least with this function, if I made any change to user.uid, React's hot reload would refresh the page, and it would bring in the queried data in the console, yet when I F5 the page, the data was not showing with the error message listed above.
Also, when I use the query builder in Firestore with the same parameters, I am able to pull the data I want to display, it is just not pulling/displaying as wanted in my react app.
Any help would be appreciated.
You are getting this error because your user is null.
Try to print value of user before accessing id. 👈 You'll know the value of user
Try to wrap your user.id with if(user) user.id. 👈 This should remove your erros

FetchError: request failed

I have a bug, i'm trying to make his tutorial for twitter clone in nextjs+tailwindcss+typescript
https://www.youtube.com/watch?v=rCselwxbUgA&t=1357s&ab_channel=SonnySangha
1:42:05 / 3:17:52
I did exactly the same but i feel like my IDE or my nextJS version is making things different
import { Tweet } from "../typings"
export const fetchTweets = async () => {
const res = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/getTweets/`)
const data = await res.json();
const tweets: Tweet[] = data.tweets;
return tweets
}
FetchError: request to https://localhost:3000/api/getTweets/ failed,
reason: write EPROTO 140020696905664:error:1408F10B:SSL
routines:ssl3_get_record:wrong version
number:../deps/openssl/openssl/ssl/record/ssl3_record.c:332:
This error happened while generating the page. Any console logs >will be displayed in the terminal window.
import { Tweet } from "../typings"
export const fetchTweets = async () => {
if(global.window) {
const res = await
fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/getTweets/`)
const data = await res.json();
const tweets: Tweet[] = data.tweets;
return tweets
}
}
Server Error Error: Error serializing .tweets returned from
getServerSideProps in "/". Reason: undefined cannot be serialized
as JSON. Please use null or omit this value.
If someone can help me <3 thanks
FIXED :
.env.local
i writed
NEXT_PUBLIC_BASE_URL=https://localhost:3000/
change https:// by http:// and yarn run dev again
NEXT_PUBLIC_BASE_URL=http://localhost:3000/

React & Sanity - Fetch Error: invalid JSON response body

I have been following a tutorial on youtube to build a twitter-clone website. However, when trying to fetch tweets from Sanity I am getting this error. I even git cloned the repo of the person that made the tutorial and I'm still getting the same error. This leads me to believe it is an issue with my VS code and not the code itself, if anyone has any suggestions that would be great thank you.
// fetchTweets.ts
export const fetchTweets = async () => {
const res = await fetch(`http://localhost:3001/api/getTweets`)
const data = await res?.json()
const tweets: Tweet[] = data.tweets
console.log('fetching', tweets)
return tweets
}
// index.tsx
export const getServerSideProps: GetServerSideProps = async (context) => {
const tweets: Tweet[] = await fetchTweets()
return {
props: {
tweets,
},
}
}
That error is typically caused by trying to render HTML as JSON—and particularly, when JSON is expected but instead an API returns an error page. Is your server definitely running on port 3001? Fetching from a non-existent server is likely consistent with this error.

Error about Prisma in Remix's Jokes App tutorial

In Remix's Jokes App tutorial, I got an error in the process of getting a user in session.server.ts.
I think the error is about Prisma, but I don't know how to solve it.
url: https://remix.run/docs/en/v1/tutorials/jokes#authentication
TypeError: Cannot read properties of undefined (reading 'findUnique')
at login (/usr/src/app/remix-jokes/build/index.js:700:30)
at action2 (/usr/src/app/remix-jokes/build/index.js:751:26)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async Object.callRouteAction (/usr/src/app/remix-jokes/node_modules/#remix-run/server-runtime/data.js:36:14)
at async renderDocumentRequest (/usr/src/app/remix-jokes/node_modules/#remix-run/server-runtime/server.js:216:24)
at async requestHandler (/usr/src/app/remix-jokes/node_modules/#remix-run/server-runtime/server.js:55:20)
at async /usr/src/app/remix-jokes/node_modules/#remix-run/express/server.js:45:22
It seems to occur in the findUnique call in the following code.
export async function login({
username,
password
}: LoginForm) {
const user = await db.user.findUnique({
where: { username }
});
if (!user) return null;
const isCorrectPassword = await bcrypt.compare(
password,
user.passwordHash
);
if (!isCorrectPassword) return null;
return user;
}
I restarted the Docker container and that solved the problem.
Thank you.

Resources