I am trying to attach a JWT token from AWS Cognito to Uppy requests in my upload component. To get the token, I believe I need an async function:
async function getSessionToken() {
const data = (await Auth.currentSession()).getAccessToken().getJwtToken()
console.log(data)
return data;
}
However, I need the value of getSessionToken
(ie. the actual token) before I initialize my Uppy component. To do this, I thought it would be best to use useEffect
, whereby I could set the state of a variable using useState
and render the Uppy component after getSessionToken
returned a value:
const [tokenData, setTokenData] = useState();
useEffect(() => {
console.log(tokenData)
getSessionToken().then((token) => { setTokenData(token) })
}, []);
return (
<>
{tokenData === 'undefined' ? <Skeleton variant="rectangular" width={210} height={118} />
: <UppyComponent data={tokenData} />}
</>
)
where UppyComponent
is:
function UppyComponent(props) {
console.log(props.data)
const uppy = useUppy(() => {
return new Uppy({
debug: true,
autoProceed: false,
restrictions: {
maxNumberOfFiles: 1,
minNumberOfFiles: 1,
allowedFileTypes: ['video/*'],
requiredMetaFields: ['caption'],
}
})
.use(AwsS3Multipart, {
limit: 4,
companionUrl: 'http://localhost:3020/',
companionHeaders: {
'Authorization': "Bearer " + props.data,
'uppy-auth-token': "Bearer " + props.data,
}
})
.use(GoldenRetriever)
.on('complete', result => {
console.log('successful files:', result.successful)
console.log('failed files:', result.failed)
})
})
return <Dashboard
uppy={uppy}
plugins={['DropTarget']}
inline={true}
target='.DashboardContainer'
showProgressDetails={true}
note='Video only, up to 1 MB'
width='400'
metaFields={[
{ id: 'name', name: 'Name', placeholder: 'Give your work a title. ' },
{ id: 'caption', name: 'Caption', placeholder: 'describe what the image is about' }
]}
browserBackButtonClose={false}
/>
}
However, I noticed that UppyComponent
is still being initialized/rendered before getSessionToken
returns. Looking at the requests, I see that props.data
is still undefined in UppyComponent
. I had thought, since useEffect wouldn’t set the state variable until after getSessionToken
returned, props.data
wouldn’t set until getSessionToken
did as well. Is this not the case?
And is there a workaround?