I know relay can inject a network layer when bootstrapping like below:
Relay.injectNetworkLayer(
new Relay.DefaultNetworkLayer('http://example.com/graphql', {
headers: {
Authorization: 'Basic SSdsbCBmaW5kIHNvbWV0aGluZyB0byBwdXQgaGVyZQ==',
},
})
);
But how about if I need to tell what the header is later(like after signing in)?
I found a simple trick. You can pass in headers object and update its pointer value.
const headers = {
Authorization: '',
};
Relay.injectNetworkLayer(
new Relay.DefaultNetworkLayer('http://example.com/graphql', {
headers: headers,
})
);
// To update the authorization, set the field.
headers.Authorization = 'Basic SSdsbCBmaW5kIHNvbWV0aGluZyB0byBwdXQgaGVyZQ=='
Great question. I imagine you're setting the network layer in your base component file. You could create a function wrapping the Relay.injectNetworkLayer call that updates the Auth header when you need to.
When loading the app, you could do something like this:
export function setNetworkLayer() {
return new Promise((resolve, reject) => {
var options = {};
if (localStorage.authToken) {
options.headers = {
Authorization: 'Basic ' + localStorage.authToken
}
}
else {
options.headers = {};
}
Relay.injectNetworkLayer(
new Relay.DefaultNetworkLayer('http://example.com/graphql', options)
);
resolve(options);
});
})
}
And if you wanted to update the network layer, you'd do something like this:
loginUser().then((res) => {
localStorage.authToken = res.token;
setNetworkLayer();
return;
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With