How to integrate getAccessToken with fetch function to load data from DRF backend to React Frontend?

React newbie here, but proficient in Django.I have a simple fetch function which worked perfectly but then my project had no login authentication involved. Now that I have configured the login system, my backend refuses to serve requests with any access tokens. My login authentication is very new to me and was more or less copied from somewhere. I am trying to understand it but am not able to. I just need to know how to convert my simple fetch function to include the getAccessToken along the request in it's headers so my backend serves that request.

Here is my previously working simple fetch function :

class all_orders extends Component {
  state = {
    todos: []

  async componentDidMount() {
    try {
      const res = await fetch(''); // fetching the data from api, before the page loaded
      const todos = await res.json();
    } catch (e) {

My new login JWT authentication system works perfectly, but my previous code is not working and I keep getting error

"detail": "Authentication credentials were not provided."

This is is the accesstoken I am not able to 'combine' with my preivous fetch function:

const getAccessToken = () => {
    return new Promise(async (resolve, reject) => {
        const data = reactLocalStorage.getObject(API_TOKENS);

        if (!data)
            return resolve('No User found');

        let access_token = '';
        const expires = new Date(data.expires * 1000);
        const currentTime = new Date();

        if (expires > currentTime) {
            access_token = data.tokens.access;
        } else {
            try {
                const new_token = await loadOpenUrl(REFRESH_ACCESS_TOKEN, {
                    method: 'post',
                    data: {
                        refresh: data.tokens.refresh,
                access_token = new_token.access;
                const expires = new_token.expires;

                reactLocalStorage.setObject(API_TOKENS, {
                    tokens: {
                        access: access_token
                    expires: expires

            } catch (e) {
                try {
                    if ( === "token_not_valid")
                } catch (e) {
                    // pass

                return reject('Error refreshing token', e);

        return resolve(access_token);



If you're looking for a way how to pass headers in fetch request, it's pretty straight forward:

await fetch('', {
 headers: {
   // your headers there as pair key-value, matching what your API is expecting, for example:
   'details': getAccessToken()

Just don't forget to import your getAccessToken const, if that's put it another file, and I believe that would be it. Some reading on Fetch method


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.