0

how can I add current user id to the axios.get request url in the front end code?

here are my codes;

backend: urls.py

urlpatterns = [
    path('<int:pk>/', UserDetail.as_view()),
]

and views.py

class UserDetail(APIView):
    permission_classes = [AllowAny]
    http_method_names = ['get', 'head', 'post']
    """
    Retrieve, update or delete a user instance.
    """
    def get_object(self, pk):
        try:
            return NewUser.objects.get(pk=pk)
        except NewUser.DoesNotExist:
            raise Http404

    def get(self, request, pk, format=None):
        user = self.get_object(pk)
        serializer = CustomUserSerializer(user)
        return Response(serializer.data) 

frontend:

useEffect(() => {
    if (localStorage.getItem("access_token")) {
      axiosInstance.get('users/**???**').then((obj) => {
       {
        setname(obj.username)
        setemail(obj.email)
        setidx(obj.uid)
        }
        console.log(obj);
        console.log(obj.data);
          setTimeout(() => {
          props.resetProfileFlag();
        }, 3000);
      }); 
    }
    
  }, [props.success])

If I add user id manually (like say; axiosInstance.get('users/1').then((obj) => { ...) it gets the user details.

MatthewJs
  • 1
  • 2

2 Answers2

0

in your axios part you need to use params like these:

useEffect(() => {
    if (localStorage.getItem("access_token")) {
      axiosInstance.get('users/',
      {
      params: {
                id: '1'
              }
        }).then((obj) => {
       {
        setname(obj.username)
        setemail(obj.email)
        setidx(obj.uid)
        }
        console.log(obj);
        console.log(obj.data);
          setTimeout(() => {
          props.resetProfileFlag();
        }, 3000);
      }); 
    }
    
  }, [props.success])

and in the backend side you can get the data also from the request.params .

rassakra
  • 1,062
  • 5
  • 9
0

Thank you Rassaka, however, still I can't get a single user details, but I get the list of all users data at the console.

I moved to DRF Viewsets and HyperlinkedModelSerializers:

class UserSerializer(serializers.HyperlinkedModelSerializer):
posts = serializers.HyperlinkedRelatedField(
    many=True, 
    queryset=Post.objects.all(),
    view_name='blog:post-detail',
)
url = serializers.HyperlinkedIdentityField(view_name='users:user-detail')


class Meta:
    model = User
    fields = ('url', 'id', 'user_name', 'email', 'posts')

views.py :

class UserViewSet(viewsets.ReadOnlyModelViewSet):
"""
This viewset automatically provides `list` and `detail` actions.
"""
permission_classes = [AllowAny]
queryset = User.objects.all()
serializer_class = UserSerializer
#lookup_field = 'pk'


def post(self, request):
    try:
        refresh_token = request.data["refresh_token"]
        token = RefreshToken(refresh_token)
        token.blacklist()
        return Response(status=status.HTTP_205_RESET_CONTENT)
    except Exception as e:
        return Response(status=status.HTTP_400_BAD_REQUEST)

urls.py:

urlpatterns = [

router.register(r'users/<int:pk>', views.UserViewSet),
router.register(r'users', views.UserViewSet),
] 
urlpatterns = [ re_path(r'^', include(router.urls)) ]

and finally my react frontend:

const UserProfile = props => {  
  const [data, setData] = useState({
        users: [],
    });

  useEffect(() => {
    if (localStorage.getItem("access_token")) {
      axiosInstance.get('users/', {params: { id: '1'}}).then((res) => {
        setData({
          users: res.data,
        })
        console.log(res.data);
        setTimeout(() => {
          props.resetProfileFlag();
        }, 3000);
      })
      .catch(err =>{
        console.log(err)
      })
    }
  }, [setData], [props.success])

  return (
    <React.Fragment>
      <div className="page-content">
        <Container fluid>
          <Row>
            <Col lg="12">
              <Card>
                <CardBody>
                  <div className="d-flex">
                    <div className="ms-3"> 
                      <img
                        src={data.users.avatar}
                        alt=""
                        className="avatar-md rounded-circle img-thumbnail"
                      />
                    </div>
                    <div className="align-self-center flex-1">
                      <div className="text-muted">
                        <h5>Username: {data.users.user_name} {''}</h5>
                        <p className="mb-1">Email: {data.users.email} {''}</p>
                        <p className="mb-0">Id no: {data.users.id} {''}</p>
                      </div>
                    </div>
                  </div>
                </CardBody>
              </Card>
            </Col>
          </Row>
        </Container>
      </div>
    </React.Fragment>
  )
}

export default UserProfile

The issue is; after login I get the right user data in the console, however, when I go to the user profile page, firstly I get this error message "GET http://127.0.0.1:8000/api/users/?id=1 401 (Unauthorized)" in the console and of course in the backend terminal. But immediate after that the backend refreshs the token ""POST /api/token/refresh/ HTTP/1.1" 200" -> "GET /api/users/?id=1 HTTP/1.1" 200". But I get all user Arrays(data) - (not the logged-in user data) in the console, however, the user profile page cannot retrieve any user data. So I can not understand if user data cannot be retrieved to the profile page because the axiosInstanse refreshes token after login or because my frontend design is wrong. Or something is wrong with the backend?? Please, your advices? ...

MatthewJs
  • 1
  • 2