I have created signalR connection in my ReactJS application, whenever i load page for the first time then i get an error "Error: Failed to complete negotiation with the server: Error: Unauthorized" but when i refresh the page again then it start working fine i.e. it get connected properly.
I just want to connect the signalR connection instantly when page load for the first time without the need to refresh it again.
P.S I think connection is trying to connect immediately without waiting for the accessToken to get fetched.
How can i fix this issue in my code?
Here is my code for signalR connection:
export default class Dashboard extends Component {
constructor(props) {
super(props)
this.state = {
signalRURL: 'https://****/?hub=broadcast',
accessToken: '',
alertData: {}
}
}
getURL = () => {
return new Promise((resolve, reject) => {
return axios({
url: 'https://*****/api/SignalRConnection',
method: "get",
headers: {
"content-type": "application/json",
"Access-Control-Allow-Origin": "*"
},
})
//Get the SignalR connection information which contains Url and Access token,
//by calling the SignalRConnection API.
.then(response => {
localStorage.setItem("access_key", response.data.accessToken)
console.log("response", response)
resolve(response);
})
.catch(error => {
reject(error);
});
});
}
componentDidMount = () => {
this.getURL().then(data => {
console.log("dataaa", data)
})
.catch(err => {
console.log("error", err)
})
//Create the Hub connection using SignalR.HubConnectionBuilder.
const options = {
accessTokenFactory: () => localStorage.getItem("access_key")
};
const hubConnection = new SignalR.HubConnectionBuilder()
.withUrl(this.state.signalRURL, options)
.configureLogging(SignalR.LogLevel.Information)
.build();
hubConnection.on('notify', data => {
this.setState({alertData: data})
console.log("state data",this.state.alertData)
console.log(data);
});
hubConnection
.start()
.catch(
error => console.error(error)
);
hubConnection.serverTimeoutInMilliseconds = 6000000;
hubConnection.keepAliveIntervalInMilliseconds = 3000000;
hubConnection.onclose((error) => {hubConnection.start();
console.error(`Something went wrong: ${error}`); });
}
render() {
return (
<div>
</div>
)
}
}
This is the error message i get everytime when i load the page for the first time