Home > front end >  How do i pass a bearer token coming from Context API into an axios call that's in a useEffect?
How do i pass a bearer token coming from Context API into an axios call that's in a useEffect?

Time:11-14

i'm looking for some help on how i can pass a bearer token, inside of a useEffect.

The token i'm getting is comming from a context, that is updated when the admin logs in.

I need to use the token as a bearer in another document, so i can get an API response back that requires the bearer.

The bearer is used for authorization, to confirm the person logging in is an admin.

Here is what i have tried so far.

Tho i still get a 401 bad request, because the bearer is not properly passed.

// React
import React, { useContext, useState, useEffect } from "react";

// Axios
import Axios from "axios";

// Contexts
import { LoginDataContext } from "../Contexts/LoginContext";
import { TokenDataContext } from "../Contexts/TokenContext";
import { UserIdDataContext } from "../Contexts/UserIdContext";

// Icons
import { HiArrowNarrowUp, HiArrowNarrowDown} from "react-icons/hi";

const AdminDashboard = () => {
  const { user } = useContext(LoginDataContext);
  const { token } = useContext(TokenDataContext);
  const { userid } = useContext(UserIdDataContext);

const header = {
    'Authorization': `Bearer ${token}`, 
}

  const [Subscriber, SetSubscriber] = useState([]);
  useEffect(() => {
    Axios.get(`http://localhost:4000/api/v1/subscribers`, { header }).then((res) => {
      console.log(res.data);
      SetSubscriber(res.data);
    });
  }, []);

CodePudding user response:

try wrapping the authorization in the headers object

const header = {
    headers: {
      Authorization: `Bearer ${token}`,
    }
}

useEffect(() => {
    Axios.get(`http://localhost:4000/api/v1/subscribers`, header).then((res) => {
      console.log(res.data);
      SetSubscriber(res.data);
    });
  }, []);
  • Related