redux-oidc: How do I set up proper API calls, after the user refreshes the application and the user object already exists
Hi,
I’m mentally stuck how to tackle my problem properly. I use redux-oidc to authorize myself, user is set up by the library and I can do my API calls with the user token in the state, like this:
// API requests - done with redux-thunk
export function fetchData() {
return function(dispatch, getState) {
const token = getState().oidc.user.access_token;
if (token === '') {
return;
}
dispatch(requestData());
const request = new Request(fetchDataUrl, {
method: 'GET',
headers: getAuthHeader(token)
});
return fetch(request)
.then(response => response.json())
.then(json => {
if (json.StatusCode !== 200) {
triggerNotification(json.StatusCode, json.ResponseMessage);
}
return json;
})
.then(json => dispatch(receiveData(json)))
.catch(() => {
triggerNotification(900);
});
};
}
The problem is, when the user reloads the page, there is no user in the state, because the middleware is not yet finished with adding the user to it.
Using it like this in a component:
class Data extends Component {
componentWillMount() {
this.props.fetchData().then(() => {
this.props.sortData(this.props.sort.column, this.props.sort.direction);
});
}
....
I don’t know how to tackle that problem. I was thinking about the userManger.getUser().then() promise, but I wasn’t able to make it work yet. Any ideas what to pay attention to?
Is there a hook in the library to only do the fetchData when the user is loaded into the state?
I hope it’s ok if I ask that here.
About this issue
- Original URL
- State: closed
- Created 7 years ago
- Comments: 15 (7 by maintainers)
I believe I found my issue. I’m still learning React so I didn’t have full grasp of the life cycle. When componentDidMount (which has our call our to external api) was firing the oidc.user wasn’t available. The component didn’t have mapStateToProps adding that and moving the api call to componentWillReceiveProps solved my issue.