How I can display only one object from API array Reactjs - reactjs

How I can display only one object from [data.hits]? Ive tried map(), filter, also setRecipes([data.hits.recipe[0]]); etc ... and it doesn't work. Currently, it shows 10 objects on the website but I need only one. Thank you for any help.
const [recipes,setRecipes] = useState ([]);
useEffect(()=>{
getReciepes();
},[query]);
const getReciepes = async () => {
const response = await fetch (`https://api.edamam.com/search?
q=${query}&app_id=${APP_ID}&app_key=${APP_KEY}`);
const data = await response.json();
setRecipes(data.hits);
console.log(data.hits);}

I dont know how I did not notice this. Here is a simple solution :
const list=[...data.hits]
list.length = 1
setRecipes(list);
console.log(list);
}

Related

React.js Object fetched into Context from Firestore is undefined, when using it in another component

I am facing a problem, as I am trying to use variable, which is being fetched in Context. And it's not a first time I had this problem, so seems like I am missing some crucial concept in React.
In my Context I am fetching object from firestore and setting it as a state. I worked with this fetched object before, so I know that problem is not in fetching or object structure.
const [products, setProducts] = useState([])
const [filteredProducts, setFilteredProducts] = useState([])
useEffect(() => {
const getCategoriesMap = async () => {
const categoryMap = await getCategoriesAndDocuments('categories')
const all = await Object.values(categoryMap).reduce((acc, arr) => acc.concat(arr), [])
setProducts({ all, ...categoryMap })
}
getCategoriesMap()
setFilteredProducts(products['all'])
}, [])
But as I am trying to use state with this object in another component - I get error 'Cannot read properties of undefined'.
For example here:
const { products } = useContext(ProductsContext)
const newCollection = products?.all?.filter(product => product.new === true)
Or here:
const maxSteps = newCollection?.length
return (
<div className='new-img' style={{ backgroundImage:`url(${newCollection[activeStep]?.imgUrl})` }}></div>
)
Could somebody tell me the reason why the state is undefined, or even better provide with some useful links to read on this topic.

Firebase, trying to pull the collection based on a ID?

Basically, I have two collections per post. One with the comments on the post and one with the post information. The formula I wrote gives me the data of the post information. I want it to return both collections so I can map through the comment collection. but I cannot seem to figure out how to get it to send me to one level up basically. Any help would be appreicated!
const docRef = doc(db, "posts", postId);
useEffect(() => {
if(postId){
const getUsers = async () => {
const data = await getDoc(docRef)
console.log(data.data())
}
getUsers()
}
}, [])
The answer I was looking for is as follows!
const stepOne = collection(db,"posts")
const stepTwo = doc(stepOne,postId)
const stepThree = collection(stepTwo,"comments")
const stepFour = onSnapshot(stepThree,((snapshot)=>snapshot.docs.map((doc)=>console.log(doc.data()))))
Through this structure on the picture, comments are a collection nested inside posts, right? If so, then you cannot return a subcollection from a simple query on the parent document. Try fetching the post info first, then fetch the comments from an other query
this is for posts:
const docRef = doc(db, "posts", postId);
the path for comment will be
"posts/postId/comment"

How to share data from useState in React to another Component

Hey guys let me quickly explain my problem.
I currently have Component in which User can Search something. And after they Click on a Button I get the Data from Firebase which is then stored in a useState which I map afterwards. This whole operation is in one function.
But for now I show the result at the same Page because I dont know how to transfer the data in the useState to the other component.
const handleClick = async () => {
const kurzRef = collectionGroup(db, 'kurzwaffensub' );
const MOD = query(kurzRef,where("kurzModell", "==", `${kurzModell}` ));
if(kurzModell) {
const getWaffenDaten = async () => {
const modell = await getDocs(MOD);
const data = [];
for (const doc of modell.docs) {
const parentDoc = await getDoc(doc.ref.parent.parent);
const { Name, avatar,avatarPath, Erfahrung, Adresse, Schützenverein } = parentDoc.data();
const waffenbilderRef = collection(db, 'users', doc.data().uid, 'waffenbildersub')
const subCollectionDocs = await getDocs(waffenbilderRef)
const subCollectionData = subCollectionDocs.docs.map((doc) => {
return { id: doc.id, ...doc.data()}
})
data.push({
...doc.data(),
Name,
subCollectionData,
avatar,
avatarPath,
Erfahrung,
Adresse,
Schützenverein
});
}
setTest(data)
}
getWaffenDaten()
}
After that operation I just return the Result in the same Page . And I want to change the page after the onClick event with the Result. Because I dont want to see the User Interface of the Search Component.
Perhabs its pretty simple but Im still a beginner and would be very glad if you can help me out and teach me something new and important.
You can do this in multiple ways:
You can pass search query as URL parameter if you using router and fetch the data from result page
You can use state management tool like Redux or built in context api.

duplicate entry while using push on array

The collaborators contain 3 data already and I am trying to push a user which should come first. I am baffled while I tried to use console.log(), I am getting 3 response values instead one. As illustrated below; it referenced to the line 25 and it printed trice.
However, when I pushed to collaborator, I am expecting a value but I got two data values pushed to collaborator. I just want one. I have spent several hours trying to figure what I have done wrongly. Please, I don't know how, that is why I posted here.
const resData = async() => {
const res = await directus.users.me.read()
const result = res.data
console.log(result)
collaborators.push(result)
}
resData()
I finally solved it by using useEffect.
useEffect(() => {
const resData = async() => {
const res = await directus.users.me.read()
const result = await res.data
collaborators.unshift(result)
}
resData()
},[collaborators])

In react, object is seems to be as an empty object for using fetch

If I use a variable instead of using react state object inside a function is behaving weirdly for fetch. If i remove the const response..... and const data.... line things works just fine but If i use fetch function and use normal variable without using state this doesn't work. Why is that?
Object is showing normal if i log it from inside the function
Object is also showing normal if i use const variable
Object is showing like an empty object if i log it from outside the function
But this code works just fine..
const [services, setServices] = useState([]);
useEffect(() => {
const API_URL = "http://localhost:8080/getServiceName/3";
const loadData = async () => {
const apiData = [];
const response = await fetch(API_URL);
const data = await response.json();
data.services.map(service => (
apiData.push(service.service_name)
));
setServices(apiData);
}
loadData();
}, [location])
And notice that i can add more value to a const variable(const dummyLocation{in image} and const apiData in code)!, How??
loadData(); is asynchronous, so if you do
loadData()
console.log(dummyLocation)
then the console.log will happen before loadData completed. You probably just want to do
loadData().then(() => console.log(dummyLocation))
As for the questions regarding why you can do:
const apiData = [];
// ...
apiData.push(service.service_name)
the reason is that const doesn't mean the variable can't change (per se), but instead that the variable will never be reassigned - you can't do:
const apiData = [];
apiData = [service.service_name];
because that is assigning a new array to it.

Resources