ReactFix
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • React
  • React Native
  • Programming
  • Object Oriented Programming

Sunday, November 13, 2022

[FIXED] How do i pass a bearer token coming from Context API into an axios call that's in a useEffect?

 November 13, 2022     bearer-token, react-context, react-hooks, reactjs   

Issue

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);
    });
  }, []);

Solution

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);
    });
  }, []);


Answered By - Matias Bertoni
Answer Checked By - - Marie Seifert (ReactFix Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post Home

Featured Post

Is Learning React Difficult?

React is difficult to learn, no ifs and buts. React isn't inherently difficult to learn. It's a framework that's different from ...

Total Pageviews

Copyright © ReactFix