I'm currently using react-native-secure-storage to store JWTs for my user. The app retrieves data from an Express API so when making an HTTP request I retrieve the token from secure storage and when the async function completes the token is sent it to the API. I've run into a problem now which is that I want to make a component with an image in it served from the API but I can't get the JWT in an async function since the component needs to return immediately. My question is can I just temporarily store the JWT in a variable or in component state?
CodePudding user response:
Yes, you can store it in a variable, in a context, or in a state. I would recommend using React.context() to propapate your JWT token.
Example:
const JwtStuffContext = React.createContext({
jwt: null,
});
const YourApp = () => {
const theToken = 'abc';
return <JwtStuffContext.Provider value={{ jwt: theToken }}>
{/** The rest of your app, or {children} */}
</JwtStuffContext.Provider>
}
const SomewhereDownTheReactTree = () => {
const { jwt } = useContext(JwtStuffContext);
}
Note that if you wanted to avoid sharing the JWT directly with your entire application, you could a function in your state that would proxy your API requests.
However, as you mentioned displaying an image, you could create a special Picture component that fetches the token from your store, and then requests the image from the API. Like so:
const Picture = ({ placeholderSrc, getSrcWithToken }) => {
const [token, setToken] = useState(null);
useEffect(() => {
const token = await yourFunctionToFetchTokenFromstore();
setToken(token);
}, [finalSrc]);
return <img src={token !== null ? getSrcWithToken(token) : placeholderSrc } />;
}
The above would display the placeholderSrc
for as long as the token is unknown, when the token is known, it would call the prop function getSrcWithToken
passing the token, allowing you to construct the URL if you need to.