@connect
works great when I'm trying to access the store within a react component. But how should I access it in some other bit of code. For eg: let's say I want to use an authorization token for creating my axios instance that can be used globally in my app, what would be the best way to achieve that?
This is my api.js
// tooling modules
import axios from 'axios'
// configuration
const api = axios.create()
api.defaults.baseURL = 'http://localhost:5001/api/v1'
api.defaults.headers.common['Authorization'] = 'AUTH_TOKEN' // need the token here
api.defaults.headers.post['Content-Type'] = 'application/json'
export default api
Now I want to access a data point from my store, here is what that would look like if I was trying to fetch it within a react component using @connect
// connect to store
@connect((store) => {
return {
auth: store.auth
}
})
export default class App extends Component {
componentWillMount() {
// this is how I would get it in my react component
console.log(this.props.auth.tokens.authorization_token)
}
render() {...}
}
Any insights or workflow patterns out there?
api
inApp
class and after getting the authorization token you can doapi.defaults.headers.common['Authorization'] = this.props.auth.tokens.authorization_token;
, And at the same time you can store it in localStorage as well, so when the user refreshes the page, you can check if the token exists in localStorage and if it does, you can set it., I think it will be best to set the token on api module as soon as you get it. – Dhruv Kumar Jha