2

I am working on a react application, where i am checking for the availability of token in local storage, based on the token existence i need to set the headers.

I have tried by initially initializing the JavaScript object outside the loop and then set the headers in the if else condition.

getAllTopics() {
       const token = localStorage.getItem('authKey');
       var config = {};

       if(token){
         const URL = API_URL + `api/get-home-ideas-auth`;
          var config = {
           'Accept' : 'application/json',
           'Authorization' : `Bearer ` + token
       }

       } else {
         const URL = API_URL + `api/get-home-ideas`;
            var config = {
           'Accept' : 'application/json'
       }

       }
         axios.get(URL, {headers : config})
           .then(res => {
             if (res.data && res.data.status === 1) {
               const topics = res.data.data;
               console.log(topics);
               this.setState({ topics: topics, showloader:false});
             } 

           })
           .catch(e => {console.error(e); throw e;});
       }

I am getting error Cannot GET /function URL()[nativecode]

3
  • 1
    You should set the first config and then set it directly inside the condition. Basically you created 3 different config variables at different scopes and the one that is used it the first one. Commented Jul 9, 2019 at 8:19
  • You don't have to concatenate using + if you're using template literals` 'Authorization' : `Bearer ${token}`` Commented Jul 9, 2019 at 8:20
  • @techguru, see my solution below and let me know if that helps you. :) Commented Jul 9, 2019 at 8:35

3 Answers 3

2

This is a scoping issue, the problem is you initialize a new config variable inside the if-else blocks instead of referencing the one already defined outside of the scope. The new config variable is not accessible outside the private if-else scope. The outer config is never actually updated.

Just refer to the original config like so:

getAllTopics() {
   const token = localStorage.getItem('authKey');
   var config = {};
   var URL = '';
   if(token){
     URL = API_URL + "api/get-home-ideas-auth";
      config = {
         'Accept' : 'application/json',
         'Authorization' : `Bearer ${token}`
      }

   } else {
     URL = API_URL + "api/get-home-ideas";
        config = {
          'Accept' : 'application/json'
        }
   }

     axios.get(URL, {headers : config})
       .then(res => {
         if (res.data && res.data.status === 1) {
           const topics = res.data.data;
           console.log(topics);
           this.setState({ topics: topics, showloader:false});
         } 

       })
       .catch(e => {console.error(e); throw e;});
   }
Sign up to request clarification or add additional context in comments.

1 Comment

Hi @Christopher Ngo thanks for the help, there was a scoping issue with URL variable also, i updated your answer
1
getAllTopics() {
   const token = localStorage.getItem('authKey');
   const URL = API_URL + `api/get-home-ideas-auth`;
   var config = {
   'Accept' : 'application/json',
   ...(token && {'Authorization' : `Bearer ` + token})
  }

     axios.get(URL, {headers : config})
       .then(res => {
         if (res.data && res.data.status === 1) {
           const topics = res.data.data;
           console.log(topics);
           this.setState({ topics: topics, showloader:false});
         } 

       })
       .catch(e => {console.error(e); throw e;});
   } 

Comments

0

Although already answered, the most clean way to do this is through interceptors:

/**
 * Create an Axios Client with defaults
 */
const client = axios.create({
  baseURL: API.BASE_URL,
});

/*
* Request interceptor
* Useful for refreshing token before to make a new request and get 401 responses
*/
client.interceptors.request.use(
  config => {
    const originalRequest = _.cloneDeep(config);
    // Using lodash _.set() we avoid undefined keys in path
    _.set(originalRequest, 'headers.Authorization', getAuth());
    return originalRequest;
  },
  err => Promise.reject(err),
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.