I’ve been working a full stack app, in frontend I am using react,and for Backend I am using Django….
what I want to do is when the user login it will automatically render all the posts for users he is following,
I got three models, Post, User, Following
first I must fetch data to get all followings id’s , and then I must fetch data again to get all Posts that is related to the followings ,,
I tried to do this:
Home.js
const [following,setFollowing]=useState([]);
const getFollowing = async()=>{
if(authToken){
console.log("TOKEN : ",authToken.access);
try{
let response= await fetch(`${BASE_URL}profile/following/`,{
method:"GET",
headers:{
"Content-Type":"application/json",
"Authorization":`Bearer ${authToken.access}`,
}
})
let data= await response.json()
setFollowing(data)
}catch(error){
console.log(error);
}
}
//for getting posts
const getPost= async (num)=>{
let response= await fetch(`${BASE_URL}post/${num}`,{
method:"GET",
headers:{
"Authorization":`Bearer ${authToken.access}`,
"Content-Type":"application/json"
},
})
let data= await response.json()
console.log("Fetched Posts : ", data);
}
//loop to fetch all posts
const getAllPosts=()=>{
let values=Object.values(following)
values.map(value=>(
posts.push(value[Object.keys(value)[0]])
))
var arrayLength=posts.length-1
while(arrayLength=>0){
getPost(posts[arrayLength])
arrayLength-=1 }}
what I don’t undersatand is how to fetch data multiple times, like if I have followings id’s=[4,3] how to send them to getPost method
2
Answers
To achieve fetching posts for multiple users that the current user is following, you can modify your code to loop through the list of following IDs and fetch posts for each of them. Here’s how you can modify your both function:
Take the array of following ids and map them to an array of Promises and
await
them all to resolve.Example: