Cannot read properties of undefined (reading 'params') sveltkit - sveltekit

i just upgrade svelte migration route then create +page.js file this script
export async function load({ page }) {
var songId = page.params.songId;
const itunesSearched = await fetch(
`https://itunes.apple.com/search?term=${songId}&entity=song`
);
var res = await itunesSearched.json();
var songResults = res.results[0];
return {songResults}
}
Error below
Cannot read properties of undefined (reading 'params')
TypeError: Cannot read properties of undefined (reading 'params')
at load (/src/routes/[searched]/[songId]/+page.js:2:22)

You can see the interface of the event data in the docs. It has no page property; params are a direct property of the event, so you should be able to just destructure that:
export async function load({ params }) { ...

Related

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

Axios is fetching, but JSON is not displaying or being mapped

in my code i'm trying to fetch a JSON file from an URL. The URL is being fetched (I checked Network), but it's still not displayed on the website. However, the JSON data appears in the console. I think the problem is that the JSON file isn't being mapped properly.
const Blog = () => {
const [posts, setPosts] = useState([])
useEffect(() => {
const getPosts = async () => {
const response = await axios.get(`MYURL`)
setPosts(response.data.posts)
console.log(response)
}
getPosts()
}, [])
return (
<div>
{posts.map(article => {
return(
<Blog
title={article.title}
description={article.description}
url={article.url}
urltoimage={article.urltoimage}
/>
)
})}
</div>
)
}
I get the following errors when I try to run the application.
Uncaught TypeError: Cannot read properties of undefined (reading 'map')
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'map')
Consider adding an error boundary to your tree to customize error handling behavior.
When I add a question mark before the mapping, like this:
{posts?.map(article =>
the errors don't come up anymore, but it still doesn't solve my problem.
Thanks.

firestore getting doc data issue

I trying to get the url of an image from firebase firestore, the upload goes successfully, but when I try to get the image and display it, it gives me this error:
TypeError: undefined is not an object (evaluating 'doc.push')
This is the method how I get datas:
useEffect(() => {
const result = db.collection("homeBackground").doc("bg_img").onSnapshot(snap => {
const doc = snap.doc;
setImages(doc.push(doc => doc.data()))
});
return result;
}, []);
This is how I display the image:
{
images.push((image) => {
return (
<img src={image.imageUrl} alt=""/>
)
})
}
onSnapshot() is a kind of asynchronous Observable method. You need to check are data exist then assign to any thing you want.
.onSnapshot(snap => {
if(snap.exists()) { // Some methods returns object with .exist value/function.
setImages(snap.data())
}
});
onSnapshot(snapshoot: QuerySnapshot<DocumentData> | DocumentSnapshot<DocumentData> => ...) This is what you get depending on on what you wariong on you can get generic object of querysnapshot or DocumentSnapshot.
This method will trigger when data will change in database. It returns unsubscription which you can invoke and stop observing database changes.
const unsubscription = db.collection("homeBackground").doc("bg_img").onSnapshot(snap => ...);
// later in time
unsubscription() // this will stop invoke method above.

TypeError: Cannot read properties of undefined (reading 'Contract')

TypeError: Cannot read properties of undefined (reading 'Contract')
Module.
lottery-react/src/lottery.js:9
I get this error when I serve and go to the browser
My code
import web3 from "web3";
const address = '0x------------------------------';
const abi = [{"constant":true,"inputs":[],"name":"manager","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"pickWinner","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"getPlayers","outputs":[{"name":"","type":"address[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"enter","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"players","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"}];
function test () {
console.log(web3.eth); // throws undefined
};
export default test;
I fixed it by making a minor change
update web3.eth
to new web3().eth
Instead of
const web3 = require('web3');
I needed to do this:
const Web3 = require('web3');
const web3 = new Web3();
web3.eth is undefined. Try fixing that first.
You haven't initialized your contract
kindly do it and then call your smart contract method
var contract = await new web3.eth.Contract(abi, address);

TypeError: Cannot set property 'setState' of undefined. react

I did fetch data from NYTimes API and console log them.
My initial state is {searchResponse: null}
Then set state the response
this.setState=({searchResponse:response.data});
and pass it to another component named listview_component. In that component, I handle the null value of prop.
but the response from the API did not push in searchResponse. and show the error : TypeError: Cannot set property 'setState' of undefined.
How to solve this?
please check out this code
https://github.com/shojibMahabub/news-scroller/tree/develop
this.setState = {user_input} is wrong. setState is a function it should be:
this.setState({user_input});
On top you forgot to bind your function in your constructor:
this.handle_user_input = this.handle_user_input.bind(this);
I could not find any mention of setState=({searchResponse:response.data})in your code, but it probably fails because of the same issue.
If needed to access .this convert the function to fat arrow function.
do_search = (keyword) => {
axios
.get(
url, // takes the variable url
{
params: {
api_key: api_key,
q: keyword
}
}
)
.then(response => {
console.log(response);
this.setState=({searchResponse:response.data});
})
.catch(function(error) {
console.log(error);
});
}

Resources