Reputation: 347
How can I wait for the url hook to not be empty? handleViewSheet is an on click function and I do not want to use useEffect because of the initial render. Can this be done without useEffect?
const [url, setUrl] = useState('')
const handleViewSheet = () => {
GetSheet(id).then((res) => {
if (res) {
setUrl(res);
}
});
const task = getDocument(url); // url is still empty at this point
}
Upvotes: 2
Views: 822
Reputation: 3063
It seems like a job for useEffect
to be honest, so I would recommand to consider using it (You can handle the first render within the useEffect if you want).
But if you still want to avoid using useEffect
, you can use async/await
to wait for the promise to finish before using url, along with the setUrl
call. Something like this:
const [url, setUrl] = useState('')
const handleViewSheet = async () => {
let resUrl = await GetSheet(id).then((res) => {
if (res) {
setUrl(res);
return res;
}
return '';
});
const task = getDocument(resUrl );
}
Upvotes: 1