N
N
Nikita2020-01-10 18:33:49
React
Nikita, 2020-01-10 18:33:49

How to make requests go after setting the token?

Tell me how to make requests go after setting the token?
This code just gets the token and sets it to the axios settings

getAuthToken(uuid: any) {
        return instance.post(`/account/auth_token?deviceId=${uuid}`, {
            headers: {'Accept': 'text/plain'},
        })
            .then(res => instance.defaults.headers.common['Authorization'] = `Bearer ${res.data}`)
            .catch(e => console.log(e));
    },

In the App class in the lifecycle component, I call the sled in which I execute the request above:
class App extends PureComponent<IAppProps> {

    componentDidMount(): any {
        console.log(this.props);
        this.props.getToken();
        
    }
    render() {
        return (
            <div className="App">
                <Route component={IntroSlider} path="/changePath" exact/>
                <Route component={BeginningWork} path="/start"/>
                <Route component={Work} path="/"/>
            </div>
        );
    }
}

And in the Work component, I'm already making a request for data, but the problem is that the header responsible for authorization is set after the requests.
And I get three undefined, instead of data, and then my title is displayed
nHeNo-zim9g.jpg
Tell me how to solve this one? How to wait until the header is set and then make requests to the server?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir, 2020-01-10
@Casufi

I don't see if you are using context or redux.
Set the isAuthorized flag and draw a component that makes requests only if this flag is set, then it will be possible to send requests to componentDidMount, or draw and check whether this flag is set when mounting or updating properties.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question