L_Fr
L_Fr

Reputation: 101

importing a state value from react class component

In my App.js I have this state object:

App.js

this.state = {
    headers: {
        "Content-Type": "application/json",
        "X-Requested-With": "XMLHttpRequest",
        Authorization:
            "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiwianR}
};

I want to export this.state.headers to my globalMethods.js file, which has a data posting function:

globalMethods.js

export function submitUserData() {
    fetch("http://dev.test.lt/be/api/user/data", {
        method: "POST",
        body: JSON.stringify(data),
        headers // <-- this exact variable has to be this.state.headers
    })
        .then(response => response.json())

}

Can't export headers from App.js, since export const headers = this.state.headers cannot access "this" scope.

Exports within App class are, of course, not possible.

Are there any other options?

Upvotes: 0

Views: 194

Answers (4)

Govinda Malavipathirana
Govinda Malavipathirana

Reputation: 1141

You can pass the variable when you are calling the submitUserData.js.

callingUrl = () => {
  const response = submitUserData(this.state.headers)
}

So your function should be like this...

export function submitUserData(customHeaders) {
    fetch("http://dev.test.lt/be/api/user/data", {
        method: "POST",
        body: JSON.stringify(data),
        headers: customHeaders
    })
        .then(response => response.json())

}

Upvotes: 2

adel
adel

Reputation: 3507

have you tried this:

    import React from "react"

    const header ={};
    class App extends React.Component {
    constructor(){
    super()
    this.state = {
        headers: {
            "Content-Type": "application/json",
            "X-Requested-With": "XMLHttpRequest",
            Authorization:
                "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiwianR}
    };
    }
      render() {
header = this.state.headers
return   <div/>
      }
    }


export header

Upvotes: 0

Dima Vishnyakov
Dima Vishnyakov

Reputation: 1552

You need some kind external intermediate container to do that. E. g. you can make your component save headers to localStorage or use Redux for that. Or do it backwards: export your headers from globalMethods.js and use it inside class.

Upvotes: 0

layonez
layonez

Reputation: 1785

What you need is global state analog. So my advice would be to create some plain js module named requestHelper.js with property

export const requestHeaders = headers: {
        "Content-Type": "application/json",
        "X-Requested-With": "XMLHttpRequest",}

and exporting method setHeader(name, value)

import that method into your app component, and call it on auth request success. Later get your headers from requestHelper.requestHeaders object anywhere in your app

Upvotes: 0

Related Questions