Im trying to display the titles, price, description and allergies from the strapi Api:http://localhost:1337/api/pizzasarpsborgs.
api
Not really sure how to deconstruct the res. Can someone help?
This is my current code:
export default function Menu() {
const [pizzasarpsborgs, setPizzas] = useState(['']);
async function fetchPizza() {
const res = await fetch('http://localhost:1337/api/pizzasarpsborgs');
const data = await res.json();
setPizzas(data.data);
}
useEffect(() => {
fetchPizza();
}, []);
return (
<div>
{pizzasarpsborgs.map((pizza) => (
<p key={pizza.id}>{pizza.id}</p>
))}
</div>
);
}```
can you try the following and let me know if it works.
{pizzasarpsborgs.length ? pizzasarpsborgs.map((pizza) => (
<div key={pizza.id}>
<h1>{pizza.attributes.title}</h1>
<p>{pizza.attributes.price}</p>
<p>{pizza.attributes.description}</p>
<p>{pizza.attributes.allergies}</p>
</div>
)) : null}
I don't have the development environment setup as of now, so I am writing this off the top of my head. So please let me know if any errors pop up.
Related
hope you have an amazing day!
i'm new with NextJs and i have a problem when i have to map my Firebase documents, i need to put 5 cards in my web, but i setting all the documents that i have.
this is my call ref
const [posts, setPosts] = useState([]);
useEffect(() => {
(async () => {
const callref = collection(db, "posts", limit(3));
const snapshots = await getDocs(callref);
if (posts.length < 5) {
const docs = snapshots.docs.map(doc => {
const data = doc.data()
data.id = doc.id
return data
});
setPosts(docs);
console.log(docs)
} else {
return;
}
})()
}, [])
and this is the map code in my web
{
posts.map((post) => (
<div className="contProduct">
<div className="imageProduct">
<img src={post.image}></img>
</div>
<div className="descriptionProduct">
<h3>{post.title}</h3>
<p>{post.subtitle}</p>
</div>
</div>
))
}
i tried putting an if sentense but it shows me an error, i dont know how to show only five posts.
Thank you for your time and I hope you can help me.
I'm not sure if I understand the question well, but maybe what you need is using the firestore limit() function, just like this :
const callref = collection(db, "posts", limit(3));
callRef.limit(5);
const snapshots = await getDocs(callref);
I have a function loadListings() in react native app it gets data from real time firebase database and renders it on on page in <Flatlist />
function..
let data = [];
listingRef.orderByChild("created_at").on("value", (snapshot) => {
data = [];
snapshot.forEach((listing) => {
data.push(listing.val());
});
setListings(data);
setLoading(false);
});
};
and finally
useEffect(() => {
loadListings();
}, []);
Can I use it without the effect hook?
Yes you can. Based on official documentation for useEffect hook the [] empty array at the end means what loadListings function will be executed ones when this component will be mounted.
Sometimes the app working well.
but I dont know why, sometimes the data from firebase give me blank screen instead of the data.
after I reopen the app it work.
for example,
one of my pages:
useEffect( () => {
const subscriber = firestore()
.collection('Trails')
.onSnapshot(querySnapshot => { //const querySnapshot = await firebase.firestore().collection('users').get();
const trails = [];
console.log('subscribe')
if (querySnapshot)
querySnapshot.forEach(async documentSnapshot => {
trails.push({
...documentSnapshot.data(),
key: documentSnapshot.id,
});
console.log("trails test", trails)
});
setTrails(trails);
setLoading(false);
});
return () => {subscriber()};
}, []);
I made useEffect to get the data from DB then show it, and same - sometimes give me blank and sometimes works well.
I want to publish the app but im not satisfying with this bug?
sorry for my English, I dont even know how to describe this problem better.
Please can anyone guide me through? maybe my useEffect not doing well?
I think you should use debugging.
React native documentation
Stackoverflow question
I think there's issue with the return in useEffect return is called when componeent unmounts. here's an example how i handle async data fetching:
...
const [data, setData] = useState([]);
const isCurrentView = useRef(true);
useEffect(() => {
if (isCurrentView.current === true) {
const asyncFetch = async () => {
const response = await fetch(...something) //here some Asynchronous Call Like(axios, fetch)
setData([...response]);
};
asyncFetch();
}
return () => {
isCurrentView.current = false;
};
}, []);
...
im not 100% sure if this is the VERY best approach, but i have seen similar code in places so i addopted this.
problem was solved:
the setTrails was under scope and it kept refreshing with empty data.
querySnapshot.forEach(async documentSnapshot => {
trails.push({
...documentSnapshot.data(),
key: documentSnapshot.id,
});
setTrails(trails); // <<<~~~~ put the set in this scope.
});
setLoading(false);
});
Today, I was playing around with GitHub API and I ran into the 60 calls per hour roadblock as described here - https://developer.github.com/v3/rate_limit/
For command line testing the solution is to use PAT - https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token
I am new learner but the GitHub doc was a little confusing so I had run around a lot. Github recommends the following CURL usage
curl -u GitHubUserName:personalaccesstoken https://api.github.com/users/GitHubUserName
but, then, using it in a fetch request is a challenge for there are a number of depreciation in the pipeline on how to use things.
So, the question, how best to get this working in a simple fetch call in node JS and React JS?
Eventually, I ended up with the following code block that gets it working.
import React, { useState, useEffect } from "react";
function GitHubUser({ login }) {
const [data, setData] = useState();
const [error, setError] = useState();
const [loading, setLoading] = useState(false);
useEffect(() => {
if (!login) return;
setLoading(true);
fetch(`https://api.github.com/users/GitHubUserName`,{
method: "GET",
headers: {
Authorization: `token personalaccesstoken `
}
})
.then(data => data.json())
.then(setData)
.then(() => setLoading(false))
.catch(setError);
}, [login]);
if (loading) return <h1>loading...</h1>;
if (error)
return <pre>{JSON.stringify(error, null, 2)}</pre>;
if (!data) return null;
return (
<div className="githubUser">
<img
src={data.avatar_url}
alt={data.login}
style={{ width: 200 }}
/>
<div>
<h1>{data.login}</h1>
{data.name && <p>{data.name}</p>}
{data.location && <p>{data.location}</p>}
</div>
</div>
);
}
export default function App() {
return <GitHubUser login="GitHubUserName" />;
}
The main confusion was that in some parts of GitHub documentation it keeps saying we should use username, and basic and what not. Perhaps it was only confusion for me, but this solves it.
I am new to web scraping and I was trying to create a simple web scraper using a tutorial. I did that, however, I wanted to try implementing another feature on my own. In the link (https://old.reddit.com/r/programming/), I was trying to fetch all the bullet points from the 'guidelines' (On the right side of the page). Right now, I am able to scrape and get all the information from the 'guidelines', 'info', and 'relatedReddits'. However, I was only trying to get the information from the 'guidelines'. Does anyone know how I can modify my code to access only the first ul tag under the div because right now, it accesses all. Thanks for stopping by.
const axios = require('axios');
const cheerio = require('cheerio');
const getPostTitles = async () => {
try{
const {data} = await axios.get('https://old.reddit.com/r/programming/');
//console.log(data);
const $ = cheerio.load(data);
const guidelines = [];
const postTitles = [];
// to get text in form of array
$('p.title > a').each((idx, el) => {
const postTitle = $(el).text();
postTitles.push(postTitle);
});
$('.md ul li').each((idx, el) => {
const guideline = $(el).text();
guidelines.push(guideline);
});
console.log(guidelines);
return postTitles;
}
catch(error){
throw error;
}
}
getPostTitles()
.then((postTitles) => console.log(postTitles))
.catch(err => console.log(err));
$('.md').find('ul').first().each((i, el) => {
const guideline = $(el).text();
guidelines.push(guideline);
});
This was the solution for anyone that comes here to look.