Reputation: 473
How do I pass dynamic JWT x-access-token while using an API with react? I know how to use the API using fetch method.
componentDidMount(){
fetch('http://example.com/api/admin/dailyPosts')
.then(response => response.json())
.then(response => {
this.setState({
postCount: response
})
})
}
While consoling this.state.postCount, I get an empty array as no token is provided. So how do I pass the dynamic token to this API?
Upvotes: 1
Views: 4282
Reputation: 799
When you have the token from API or generated, set it as cookie to the browser like
import { Cookies } from 'react-cookie';
Cookies.set(token, auth_token_here, {path: '/'});
Set get the cookie from the browser and set header object with the token in the request method like
import { Cookies } from 'react-cookie';
componentDidMount(){
let auth_token = Cookies.get(token)
let header_obj = {'Authorization': auth_token};
fetch(url, { headers : header_obj}).then();
}
Assuming you have the token stored in the browser or is available as props from redux
Upvotes: 2