I'm getting the first response an empty list - javascript

I'm getting data from API like this:
const [software, setSoftware] = useState([]);
const id = match.params.id;
useEffect(() => {
fetch(`http://127.0.0.1:8000/api/software/${id}/`)
.then(response => response.json())
.then(data => {
setSoftware(data)
})
}, [id]);
First response is an empty list, but the next response is my list from API. I tried to use useEffect because setSoftwares is asynchronous, but it didn't help.
So how can I get only my list?

I think you are sending incorrect id for the first time, try to console.log(id) it and check-in the console if id is valid or not.

Related

Matching post author to post in React from state

I am learning React and I have successfully mapped the post titles to a div on the page. I also need to take the "userid" from the posts and get the user's name from the users state and add it to a on the div.
I can send the userid to a function which is set to return the corresponding user but it does not show up on the page. I would appreciate a review of my code to see where I am going wrong. I can log out to the console the right user but it doesn't show up on the HTML. The second in the section is the one that is not populating I would need to do that on comments as well later on so for now I just assigned a static innerHTML for that. here is my code that I have. Thanks in advance.
export default function Posts(name) {
const [posts, setPosts] = useState([]);
const [comments, setComments] = useState([]);
const [users, setUsers] = useState([])
// get Posts
useEffect(() => {
getPosts()
.then(items => {
setPosts(items)
})
// Get all Users
getUsers()
.then(users => {
setUsers(users)
})
// Get all comments
getComments()
.then(comments =>{
setComments(comments)
})
}, [])
// get individual user by userId
const getPostAuthor = (userid)=> {
users.filter((item) =>{
if ( item.id === userid){
console.log(item.name)
return item.name
}
})
}
return ( <PostsSection> {
posts.map(item => <Post><PostTitle key ={ item.title }> { item.title } </PostTitle><PostBody key={item.body}>{item.body}</PostBody><PostFooter><p>comments:4</p><p>{getPostAuthor(item.userId)}</p></PostFooter></Post>)}
</PostsSection> )
}
users.filter is returning item.name, but getPostAuthor() does not return anything. You could put a return before your users.filter function but since Array.filter() returns an array and you want one user I'd expect that is not what you want. You could instead try Array.find

Function not getting all documents in a collection

I know there is a similar question that exists here but it doesn't really answer the question on here. My code currently on get the last two documents in a collection.
const [recipedata, setRecipeData] = useState([]);
const fetchRecipes = async () =>{
const response = fire.firestore().collection("recipes");
const data = await response.get();
data.docs.forEach(item=>{
setRecipeData([...recipedata, item.data()])
})
}
useEffect(() => {
fetchRecipes();
}, [])
Again when I print (recipedata) it only show two objects in the array. Can anyone tell me why this might be happening?
The query is correct and should fetch all the documents in the collection. You should check the the collection again. Also modifying the code like this should be better so you are updating the recipes array only once.
const [recipedata, setRecipeData] = useState([]);
const fetchRecipes = async () =>{
const response = fire.firestore().collection("recipes");
const data = (await response.get()).docs.map(doc => doc.data());
console.log(data)
//Updating only once
setRecipeData(data)
}
useEffect(() => {
fetchRecipes();
}, [])
Please share your collection as well so we can try replicating any issue if it has something to do with Firestore.

Updating react state when receiving an array of object

I am using an axios.get to make a call to my MongoDB. My response from the DB is an array of objects containing all the data from the database. I am only trying to save the username of each user to state. I am trying to set the response (res.data.username) to my state however when i log my state I am getting an empty array back. PS: There was no way to copy my response so i added an image of the response for reference, let me know if there's a better way to show the response
const [users, setUsers] = useState([]);
useEffect(() => {
axios.get('http://localhost:5000/users')
.then(res => {
if (res.data.length > 0) {
console.log(res.data)
setUsers(user => [...user, res.data.username]);
}
})
}, [])
Since users is an array, Pass the array to setUsers.
Use destructuring to for readability and simplification.
const [users, setUsers] = useState([]);
useEffect(() => {
axios.get("http://localhost:5000/users").then((res) => {
if (res.data.length > 0) {
console.log(res.data);
setUsers(res.data.map(({ username }) => username));
}
});
}, []);
res.data is an array.
to just set username from response you can try
setUsers(user => [...user, res.data.map(response => response.username)]);
setUsers(res.data.map(({ username }) => username));

How to fetch correctly from server side in Node.js

I'd like to fetch/data and serverside fetch.
But I suffered following errors.
response.getCategory is not a function
(()=>{
const url = "/data";
fetch(url)
.then(response => {
console.log("getCategory_main.js",response.getCategory(1));
//displayQuiz(response,1);
});
})();
when we access /data, serverside fetch will be functioned.
const API_KEY="https://opentdb.com/api.php?amount=1&type=multiple";
const fetch = require('node-fetch');
const Quiz=require("../public/javascripts/quiz");
module.exports={
getQuiz:function(res){
fetch(API_KEY)
.then(response => response.json())
.then(json => { const quiz = new Quiz(json);
console.log("getCategory_model",quiz.getCategory(1));
console.log("quiz",quiz);
res.send(quiz);
});
}
};
I can get result
getCategory_model History
I should pass same data from serverside to clientside
but method access succeeded only in serverside..
What is the cause of this ? and how can I fix it ? thanks..
You can't send objects with live methods over the wire as JSON. That is, if your server side Quiz object has a getCategory() method, it won't have one when you send it over to the client.
You'll need to serialize it, e.g.
res.send({
quiz,
categories: [quiz.getCategory(1)],
});
When you fetch data, your'e fetching data (usually as text).
When you create a new quiz with new Quiz(json) your'e reading the json text data and using Quiz to create code from the json text.
So in your first example you should get the text result, and then evaluate the result to json so that you can use getCategory() from Quiz
const url = "/data";
fetch(url)
.then(data => data.json())
.then(json_text=> {
// here you use the text and parse to JSON
const data = JSON.parse(json_text)
// now you can create the Quiz object
const quiz = new Quiz(data)
console.log("getCategory_main.js", quiz.getCategory(1));
});

Fetch recursion using javascript to call Google place API

I need to get a list of results from a Google place API request. The API allows 20 results per page ans I need all results available so I need to go to the next page.The next page is accessible from a token given in the response of the previous request.
I've implemented the code below:
function request(url){
return fetch(url)
.then((response) => response.json())
.catch((error) => console.log(error))
}
This is my recursive function:
export function getListOfActivitiesInACity(city_name,nextPageToken,datas){
const first_url = 'https://maps.googleapis.com/maps/api/place/textsearch/json?query=activity+in+'+city_name+'&key='+ API_TOKEN +'&language=fr'
const next_url = 'https://maps.googleapis.com/maps/api/place/textsearch/json?pagetoken='+nextPageToken+'&key='+ API_TOKEN
var url = nextPageToken ===''? first_url : next_url;
return request(url)
.then((data) => {
const newData = [...datas, data];
if(data["next_page_token"] !== undefined){
return getListOfActivitiesInACity(city_name,data["next_page_token"],newData);
}
return newData;
})
}
And then I call my function and print results
var datas=[];
getListOfActivitiesInACity("Lyon",'',datas)
.then(data => {console.log(data);})
The first iteration of the fetch works fine and gives me the good new url for the next fetch
(I tried it on my broser directy and it works)
But the second fetch return me this :
Object {
"html_attributions": Array [],
"results": Array [],
"status": "INVALID_REQUEST",
}
I really don't understand why it doesn't work , so please can anyone help Thanks

Categories

Resources