skip to Main Content

I want to get some data from an api with a parameter current user’s username.

useEffect(()=>{
        console.log(currentUser[0]?.id.toString())
        if (currentUser) {
            console.log(currentUser[0]?.id.toString())
            axios.get(`http://127.0.0.1:8000/get_chat2/?user1=${currentUser[0]?.id.toString()}&user2=`).then(res=>{
                setUsers(res.data)
                console.log(res.data)
            })    
},[currentUser])

When I print currentUser[0]?.id.toString() I get user’s id but when I send the request it is undefined. I tried doing it a string but it still is undefined. Also when instead of id I use the username it isn’t undefined.

2

Answers


  1. Is this currentUser an asynchronous value? Try the following code.

    useEffect(()=>{
            const {id} = currentUser?.[0] || {};
            if (id) {
                axios.get(`http://127.0.0.1:8000/get_chat2/?user1=${id}&user2=`).then(res=>{
                    setUsers(res.data)
                    console.log(res.data)
                })    
    },[currentUser])
    
    Login or Signup to reply.
  2. Check the API endpoint and make sure that its correctly configured to accept the "user1" and then debug to verify the value of currentUser[0]?.id.toString() just before making the GET request to ensure it’s correct.

    your modified code I think this will work.

    useEffect(() => {
        const firstUser = currentUser?.[0];
        
        if (firstUser) {
            axios.get(`http://127.0.0.1:8000/get_chat2/?user1=${firstUser.id}&user2=`)
                .then(res => {
                    setUsers(res.data);
                });
        }
    }, [currentUser]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search