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

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.

Related

Dynamic Route Handling in Next.js with Server-side Rendering causing TypeError

I am trying to implement dynamic routing in Next.js with server-side rendering, but I'm encountering an issue with TypeError. I have the following code in my pages/[id].js file:
``import React from 'react';
const Post = ({ post }) => {
return (
<div>
<h1>{post.title}</h1>
<p>{post.body}</p>
</div>
);
};
Post.getInitialProps = async ({ query }) => {
const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${query.id}`);
const post = await res.json();
return { post };
};
export default Post;`
`
When I navigate to http://localhost:3000/posts/1, I get the following error:
TypeError: Cannot read property 'title' of undefined
I'm not sure why this is happening, as the post object seems to be correctly returned from the getInitialProps method. Can someone help me resolve this issue and explain what might be causing it?

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

I am losing my api data when I refresh my react app

I am using axios to fetch and retrieve data from an api. I then set the api data to some state. When I save the changes, it shows the name from index [0] of the array, as I want. However when I refresh the page, it throws an error "Cannot read properties of undefined (reading 'name')". It seems like I am losing the api data when I refresh, what am I doing wrong here? The api endpoint is madeup, as I don't want to share the real endpoint here.
const [apiData, setApiData] = useState([]);
useEffect(() => {
axios
.get("https://some-api")
.then((res) => {
setApiData(res.data);
})
.catch((error) => {
alert(error.message);
});
}, []);
return <h1>{apiData[0].name}</h1>
try it please
return <h1>{ aapiData.length && apiData[0]?.name}</h1>
It has nothing to do with refreshing the page. This will always happen on the first render for this component.
The initial state value is an empty array:
const [apiData, setApiData] = useState([]);
And you're trying to access the first element of that array:
return <h1>{apiData[0].name}</h1>
An empty array has no first element, so it throws an error.
You can use optional chaining:
return <h1>{apiData[0]?.name}</h1>
Or perhaps check if it's there before using it:
return <h1>{apiData[0] && apiData[0].name}</h1>
Or not render anything at all if the array is empty:
return apiData.length > 0 ? <h1>{apiData[0].name}</h1> : null;

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

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 }) { ...

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.

Resources