this.props in external fetch function is undefined












0















I am using React.js for my project. I have a problem with this.props in external fetch function. Here is my code



export default function request(method, url, body) {
console.log(this); //undefined here
if (method === "GET") {
body = undefined;
}
return fetch(url, {
method,
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: "Bearer " + token
},
body
}).then(res => {
console.log(this); //undefined here
if (res.status === 401) {
this.props.history.push("/login");
return Promise.reject("Unauthorized.");
} else {
return res;
}
});
}

export const get = url => request("GET", url);
export const post = (url, body) => request("POST", url, body);
export const put = (url, body) => request("PUT", url, body);
export const del = (url, body) => request("DELETE", url, body);


If res.status ===401. I hope my program can jump back to login. However, this.props in my function is always undefined. How I can bind this with specific component?










share|improve this question























  • you have to pass the history prop to the request function or just catch the unauthorized error and do the redirect on the calling place :)

    – Baha'a Odeh
    Nov 20 '18 at 21:43











  • What do you expect this to be? And how does this relate to React? Why are you accessing this.props in the first place? Your function doesn't seem to be a React component.

    – Felix Kling
    Nov 20 '18 at 22:01


















0















I am using React.js for my project. I have a problem with this.props in external fetch function. Here is my code



export default function request(method, url, body) {
console.log(this); //undefined here
if (method === "GET") {
body = undefined;
}
return fetch(url, {
method,
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: "Bearer " + token
},
body
}).then(res => {
console.log(this); //undefined here
if (res.status === 401) {
this.props.history.push("/login");
return Promise.reject("Unauthorized.");
} else {
return res;
}
});
}

export const get = url => request("GET", url);
export const post = (url, body) => request("POST", url, body);
export const put = (url, body) => request("PUT", url, body);
export const del = (url, body) => request("DELETE", url, body);


If res.status ===401. I hope my program can jump back to login. However, this.props in my function is always undefined. How I can bind this with specific component?










share|improve this question























  • you have to pass the history prop to the request function or just catch the unauthorized error and do the redirect on the calling place :)

    – Baha'a Odeh
    Nov 20 '18 at 21:43











  • What do you expect this to be? And how does this relate to React? Why are you accessing this.props in the first place? Your function doesn't seem to be a React component.

    – Felix Kling
    Nov 20 '18 at 22:01
















0












0








0


0






I am using React.js for my project. I have a problem with this.props in external fetch function. Here is my code



export default function request(method, url, body) {
console.log(this); //undefined here
if (method === "GET") {
body = undefined;
}
return fetch(url, {
method,
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: "Bearer " + token
},
body
}).then(res => {
console.log(this); //undefined here
if (res.status === 401) {
this.props.history.push("/login");
return Promise.reject("Unauthorized.");
} else {
return res;
}
});
}

export const get = url => request("GET", url);
export const post = (url, body) => request("POST", url, body);
export const put = (url, body) => request("PUT", url, body);
export const del = (url, body) => request("DELETE", url, body);


If res.status ===401. I hope my program can jump back to login. However, this.props in my function is always undefined. How I can bind this with specific component?










share|improve this question














I am using React.js for my project. I have a problem with this.props in external fetch function. Here is my code



export default function request(method, url, body) {
console.log(this); //undefined here
if (method === "GET") {
body = undefined;
}
return fetch(url, {
method,
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: "Bearer " + token
},
body
}).then(res => {
console.log(this); //undefined here
if (res.status === 401) {
this.props.history.push("/login");
return Promise.reject("Unauthorized.");
} else {
return res;
}
});
}

export const get = url => request("GET", url);
export const post = (url, body) => request("POST", url, body);
export const put = (url, body) => request("PUT", url, body);
export const del = (url, body) => request("DELETE", url, body);


If res.status ===401. I hope my program can jump back to login. However, this.props in my function is always undefined. How I can bind this with specific component?







javascript reactjs frontend fetch






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 20 '18 at 21:22









xxddooxxddoo

396




396













  • you have to pass the history prop to the request function or just catch the unauthorized error and do the redirect on the calling place :)

    – Baha'a Odeh
    Nov 20 '18 at 21:43











  • What do you expect this to be? And how does this relate to React? Why are you accessing this.props in the first place? Your function doesn't seem to be a React component.

    – Felix Kling
    Nov 20 '18 at 22:01





















  • you have to pass the history prop to the request function or just catch the unauthorized error and do the redirect on the calling place :)

    – Baha'a Odeh
    Nov 20 '18 at 21:43











  • What do you expect this to be? And how does this relate to React? Why are you accessing this.props in the first place? Your function doesn't seem to be a React component.

    – Felix Kling
    Nov 20 '18 at 22:01



















you have to pass the history prop to the request function or just catch the unauthorized error and do the redirect on the calling place :)

– Baha'a Odeh
Nov 20 '18 at 21:43





you have to pass the history prop to the request function or just catch the unauthorized error and do the redirect on the calling place :)

– Baha'a Odeh
Nov 20 '18 at 21:43













What do you expect this to be? And how does this relate to React? Why are you accessing this.props in the first place? Your function doesn't seem to be a React component.

– Felix Kling
Nov 20 '18 at 22:01







What do you expect this to be? And how does this relate to React? Why are you accessing this.props in the first place? Your function doesn't seem to be a React component.

– Felix Kling
Nov 20 '18 at 22:01














2 Answers
2






active

oldest

votes


















0














Since the exported functions above are not components, this.props will always be unavailable. If you wanted, you could create an extra argument to accept this.props in the function and then supply this.props each time you call the functions.



Basically, you would need to write a component, that, upon being called for rendering, triggers the fetch function. As a component you could then take advantage of the withRouter function from react-router or react-router-dom. Then use:



export default withRouter(component-name)


So, any time this component is called, this.props.history becomes available, just as other props. You might as well pass any other props on the JSX tag.



Here is how it should look like:



class TryComponent extends Component {

myFetchFunction() {
//this.props.history is available
//call request, get, delete... function here and pass props
}

render() {
// call here or call from the constructor
this.myFetchFunction();

return <AnyJSX></AnyJSX>;
}
}

export default withRouter(TryComponent);


So when you write <TryComponent foo="bar" />, foo is available as a props and history is also available as a props.






share|improve this answer































    0














    I would recommend not trying to do anything react-ish within your external request() function.



    Instead, right now your request() function is returning something, therefore wherever it is called (in a react component most likely) you will be able to chain .then() onto it.



    So within the react component where it is being used:



    import { get } from '...'

    ReactComponent extends Component {

    classMethodToMakeRequest() {
    get('someurl.com').then(() => this.props.history.push('/push/route'))
    }

    }


    You will only have access to this.props from within a react component.






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53401729%2fthis-props-in-external-fetch-function-is-undefined%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0














      Since the exported functions above are not components, this.props will always be unavailable. If you wanted, you could create an extra argument to accept this.props in the function and then supply this.props each time you call the functions.



      Basically, you would need to write a component, that, upon being called for rendering, triggers the fetch function. As a component you could then take advantage of the withRouter function from react-router or react-router-dom. Then use:



      export default withRouter(component-name)


      So, any time this component is called, this.props.history becomes available, just as other props. You might as well pass any other props on the JSX tag.



      Here is how it should look like:



      class TryComponent extends Component {

      myFetchFunction() {
      //this.props.history is available
      //call request, get, delete... function here and pass props
      }

      render() {
      // call here or call from the constructor
      this.myFetchFunction();

      return <AnyJSX></AnyJSX>;
      }
      }

      export default withRouter(TryComponent);


      So when you write <TryComponent foo="bar" />, foo is available as a props and history is also available as a props.






      share|improve this answer




























        0














        Since the exported functions above are not components, this.props will always be unavailable. If you wanted, you could create an extra argument to accept this.props in the function and then supply this.props each time you call the functions.



        Basically, you would need to write a component, that, upon being called for rendering, triggers the fetch function. As a component you could then take advantage of the withRouter function from react-router or react-router-dom. Then use:



        export default withRouter(component-name)


        So, any time this component is called, this.props.history becomes available, just as other props. You might as well pass any other props on the JSX tag.



        Here is how it should look like:



        class TryComponent extends Component {

        myFetchFunction() {
        //this.props.history is available
        //call request, get, delete... function here and pass props
        }

        render() {
        // call here or call from the constructor
        this.myFetchFunction();

        return <AnyJSX></AnyJSX>;
        }
        }

        export default withRouter(TryComponent);


        So when you write <TryComponent foo="bar" />, foo is available as a props and history is also available as a props.






        share|improve this answer


























          0












          0








          0







          Since the exported functions above are not components, this.props will always be unavailable. If you wanted, you could create an extra argument to accept this.props in the function and then supply this.props each time you call the functions.



          Basically, you would need to write a component, that, upon being called for rendering, triggers the fetch function. As a component you could then take advantage of the withRouter function from react-router or react-router-dom. Then use:



          export default withRouter(component-name)


          So, any time this component is called, this.props.history becomes available, just as other props. You might as well pass any other props on the JSX tag.



          Here is how it should look like:



          class TryComponent extends Component {

          myFetchFunction() {
          //this.props.history is available
          //call request, get, delete... function here and pass props
          }

          render() {
          // call here or call from the constructor
          this.myFetchFunction();

          return <AnyJSX></AnyJSX>;
          }
          }

          export default withRouter(TryComponent);


          So when you write <TryComponent foo="bar" />, foo is available as a props and history is also available as a props.






          share|improve this answer













          Since the exported functions above are not components, this.props will always be unavailable. If you wanted, you could create an extra argument to accept this.props in the function and then supply this.props each time you call the functions.



          Basically, you would need to write a component, that, upon being called for rendering, triggers the fetch function. As a component you could then take advantage of the withRouter function from react-router or react-router-dom. Then use:



          export default withRouter(component-name)


          So, any time this component is called, this.props.history becomes available, just as other props. You might as well pass any other props on the JSX tag.



          Here is how it should look like:



          class TryComponent extends Component {

          myFetchFunction() {
          //this.props.history is available
          //call request, get, delete... function here and pass props
          }

          render() {
          // call here or call from the constructor
          this.myFetchFunction();

          return <AnyJSX></AnyJSX>;
          }
          }

          export default withRouter(TryComponent);


          So when you write <TryComponent foo="bar" />, foo is available as a props and history is also available as a props.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 20 '18 at 22:00









          Caleb LucasCaleb Lucas

          6816




          6816

























              0














              I would recommend not trying to do anything react-ish within your external request() function.



              Instead, right now your request() function is returning something, therefore wherever it is called (in a react component most likely) you will be able to chain .then() onto it.



              So within the react component where it is being used:



              import { get } from '...'

              ReactComponent extends Component {

              classMethodToMakeRequest() {
              get('someurl.com').then(() => this.props.history.push('/push/route'))
              }

              }


              You will only have access to this.props from within a react component.






              share|improve this answer




























                0














                I would recommend not trying to do anything react-ish within your external request() function.



                Instead, right now your request() function is returning something, therefore wherever it is called (in a react component most likely) you will be able to chain .then() onto it.



                So within the react component where it is being used:



                import { get } from '...'

                ReactComponent extends Component {

                classMethodToMakeRequest() {
                get('someurl.com').then(() => this.props.history.push('/push/route'))
                }

                }


                You will only have access to this.props from within a react component.






                share|improve this answer


























                  0












                  0








                  0







                  I would recommend not trying to do anything react-ish within your external request() function.



                  Instead, right now your request() function is returning something, therefore wherever it is called (in a react component most likely) you will be able to chain .then() onto it.



                  So within the react component where it is being used:



                  import { get } from '...'

                  ReactComponent extends Component {

                  classMethodToMakeRequest() {
                  get('someurl.com').then(() => this.props.history.push('/push/route'))
                  }

                  }


                  You will only have access to this.props from within a react component.






                  share|improve this answer













                  I would recommend not trying to do anything react-ish within your external request() function.



                  Instead, right now your request() function is returning something, therefore wherever it is called (in a react component most likely) you will be able to chain .then() onto it.



                  So within the react component where it is being used:



                  import { get } from '...'

                  ReactComponent extends Component {

                  classMethodToMakeRequest() {
                  get('someurl.com').then(() => this.props.history.push('/push/route'))
                  }

                  }


                  You will only have access to this.props from within a react component.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 20 '18 at 21:46









                  patmedersenpatmedersen

                  83




                  83






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53401729%2fthis-props-in-external-fetch-function-is-undefined%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      How to change which sound is reproduced for terminal bell?

                      Can I use Tabulator js library in my java Spring + Thymeleaf project?

                      Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents