noirtempest's avatar

ERROR: STATUS 401 UNAUTHENTICATED

Why is it that it that status 401?

hooks:

import axiosInstance, { getJWTHeader } from '../../utils/axiosConfig';
import { useUser } from '../hooks/useUser';

export function useJobs() {
    const [jobs, setJobs] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const { user } = useUser();

    useEffect(() => {
        const fetchJobs = async () => {
            try {
                if (!user) {

                    setLoading(false);
                    return;
                }

                console.log('User exists:', user);


                const headers = getJWTHeader(user);
                console.log('Headers:', headers);


                const response = await axiosInstance.get("auth/jobs", { headers });


                setJobs(response.data.jobs);
                setLoading(false);
            } catch (error) {
                console.error("Error fetching jobs:", error);
                if (error.response && error.response.status === 401) {
                    console.log("Token expired. Please log in again.");
                    setError("Authentication failed. Please log in again.");
                } else {
                    setError("Error fetching jobs. Please try again.");
                }
                setLoading(false);
            }
        };


        fetchJobs();


        return () => {

        };
    }, [user]);

    return { jobs, loading, error };
}```

userUser.js:

```import AsyncStorage from "@react-native-async-storage/async-storage";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import axiosInstance, { getJWTHeader } from "../../utils/axiosConfig";
import { clearStoredUser, setStoredUser } from "../user-storage";

export async function getUser(signal) {
    let user = await AsyncStorage.getItem("upcare_user");
    if (!user) {
        return null;
    }

    const { data } = await axiosInstance.get("/auth", {
        signal, // abortSignal from React Query
        headers: getJWTHeader(JSON.parse(user)),
    });
    return user ?? data;
}

export const useUser = () => {
    const queryClient = useQueryClient();
    const { data: user, isLoading, isFetching, isFetched, refetch } = useQuery({
        queryKey: ['user'],
        queryFn: ({ signal }) => getUser(signal),
        onSuccess: (received) => {
            if (!received) {
                clearStoredUser();
            } else {
                setStoredUser(received);
            }
        },
        onError: (err) => {
            console.log(err);
            clearUser();
        },
    });


    // meant to be called from useAuth
    function updateUser(newUser) {
        // update the user
        queryClient.setQueryData(["user"], newUser);
    }

    // meant to be called from useAuth
    function clearUser() {
        // reset user to null
        queryClient.setQueryData(["user"], null);
        queryClient.clear();
        clearStoredUser();
    }

    async function addPushToken(token) {
        let user = await AsyncStorage.getItem("upcare_user");
        if (!user) {
            // Logout the user
            return null;
        }
        const body = {
            pushToken: token,
        };

        const { data } = await axiosInstance.put("/auth/push-token", body, {
            headers: getJWTHeader(JSON.parse(user)),
        });
        return data;
    }

    return {
        user,
        isLoading,
        isFetching,
        isFetched,
        refetchUser: refetch,
        updateUser,
        clearUser,
        addPushToken,
    };
};

baseUrl:

const baseURL
const axiosInstance = axios.create({
    baseURL,
})

export function getJWTHeader(user) {
    return {
        Authorization: `Bearer ${user.token}`
    }
}

export default axiosInstance

I check the api there is data the only thing is that it can not fetch it always return status 401

btw Im using Laravel + React Native here, axios and jwt authentication

0 likes
2 replies
shariff's avatar

ERROR: STATUS 401 UNAUTHENTICATED means you are not passing valid token to get the details. Check whether the token is valid or not. Or You are not passing jwt token correctly.

Please or to participate in this conversation.