skip to Main Content

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


  1. 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:

    const getAllPosts = async () => {
      try {
        // Check if following is defined and not empty
        if (following && following.length > 0) {
          // Loop through each following ID
          for (let i = 0; i < following.length; i++) {
            const followingId = following[i];
            // Fetch posts for the current following ID
            await getPost(followingId);
          }
        } else {
          console.log("No following users found.");
        }
      } catch (error) {
        console.log(error);
      }
    };
    
    const getPost = async (userId) => {
      try {
        let response = await fetch(`${BASE_URL}post/?user=${userId}`, {
          method: "GET",
          headers: {
            "Authorization": `Bearer ${authToken.access}`,
            "Content-Type": "application/json"
          },
        });
        let data = await response.json();
        console.log("Fetched Posts for user ", userId, " : ", data);
      } catch (error) {
        console.log(error);
      }
    };
    
    Login or Signup to reply.
  2. Take the array of following ids and map them to an array of Promises and await them all to resolve.

    Example:

    const getPost = async (userId) => {
      try {
        const response = await fetch(`${BASE_URL}post/?user=${userId}`, {
          method: "GET",
          headers: {
            "Authorization": `Bearer ${authToken.access}`,
            "Content-Type": "application/json"
          },
        });
        const data = await response.json();
    
        console.log("Fetched Posts for user ", userId, " : ", data);
    
        return data; // <-- return fetched post data
      } catch (error) {
        console.log(error);
      }
    };
    
    const getAllPosts = async () => {
      try {
        // Assumes the following state is just the array of post ids
        const posts = await Promise.all(following.map(getPost));
    
        // do with the posts array of responses what you need to do
      } catch(error) {
        // catch/handle any thrown errors or Promise rejections
      }
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search