skip to Main Content

I currently have my userInfo stored in a state

const [users, setUsers] = useState([])

Please, how do I pass the userId into the axios URL to be able to fetch the posts of a specific user. see what I did below. I know I am getting it wrong but please help me.

Dashboard Component

const Dashboard = () => {

const getPost = () => {   

    axios.get(`/api/getpost/${users._id}`, //I want to fetch the userID on this URL. That measns it is to replace ${users._id}
     {
      withCredentials: 'true',
      headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
      }
    })
    .then((response) => {
      setUposts(response.data)
    })
  }
  useEffect(() => {
    getPost()
  }, [])


return (
//something here

)
}

UserSchema
This is my userSchema

const userSchema = new Schema({
    username: {
        type: String,
        required: true
    },
    roles: {
        User: {
            type: Number,
            default: 2001
        },
        Mentor: Number,
        Admin: Number
    },
    password: {
        type: String,
        required: true
    },
    userID: {
        type: String,
        required: true
    },
    Profile: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "profile",
    },
    refreshToken: String
});

const User = mongoose.model('user', userSchema);

module.exports = User;

API TO GET USER POST
This is how I find the user by their id from the database and populate

router.get('/getpost/:id/', (req, res) => {
    const id = req.params.id;    
    // const profID = req.params.prof_id; 
    Userpost.find({User:id}).populate('User', {password: 0}).populate('Profile').exec((err,docs) => {
        if(err) throw(err);
        res.json(docs);
    })
});

HOW I setUsers
The code below show how I did set the User in state.

 const getUser = () => {
    axios.get('/api/users', {
      withCredentials: 'true',
      headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
      }
    })
    .then((response) => {
      setUsers(response.data)
    })
  };
  useEffect(() => {
    getUser()
  }, [])

4

Answers


  1. Chosen as BEST ANSWER

    THIS WAS HOW I WAS ABLE TO FIX THIS

    Using a variable to store the userInfo which includes the UserId (_id) as recommended by Daniel. That makes it immediately available for an API call in the URL on the next line. user[0]._id.

    const getUserPost = () => {
        axios.get('/api/users', {
          withCredentials: 'true',
          headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json'
          }
        })
        .then((response) => {
         let user = response.data
    
        axios.get(`/api/getpost/` + user[0]._id, {
          withCredentials: 'true',
          headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json'
          }
        })
        .then((response) => {
         setUposts(response.data)
        })
      })
    
      };
      useEffect(() => {
        getUserPost()
      }, [])
    

  2. Replace it to:

    axios.get(/api/getpost/${users[0]._id},

    Login or Signup to reply.
  3. The Question is where do you setUsers we need to know whats inside. And specially where the setUsers is called. A state always needs time to get set. its not set just because you call it. You should try it with a let if it changes and if you need it right away

    const getUser = () => {
        axios.get('/api/users', {
          withCredentials: 'true',
          headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json'
          }
        })
        .then((response) => {
         let user = response.data
        })
      };
      useEffect(() => {
        getUser()
      }, [])
    

    just use the the variable user(like above) instead of the user State.

    useState() undefined in React just after set

    has a long and right explanation to it.

    Login or Signup to reply.
  4. Assuming that you are calling getUser() api first and setting the details of user before you call getPost() api in useEffect. You can pass userId as an argument to getPost() function. In useEffect when you call getPost(), you will have your user data and as you are storing it in array you need to access it in form of array like:

    users[0].userId.

    So you can do implement the code in this way:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
    const Dashboard = () => {
    
    const getPost = (userId) => {   
    
        axios.get(`/api/getpost/${userId}`, 
         {
          withCredentials: 'true',
          headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json'
          }
        })
        .then((response) => {
          setUposts(response.data)
        })
      }
      useEffect(() => {
        getPost(users[0].userId);
      }, [])
    
    
    return (
    //something here
    
    )
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search