My app keeps crashing the first time it loads because my setState is being fired before waiting for the data from the resolved promise.
Maybe I'm doing something wrong?
const handlePublicationTypeSelect = async (e: React.MouseEvent<HTMLButtonElement>) => {
setIsLoading(true);
await getAvailableFiles((e.target as HTMLButtonElement).value);
console.log(availableFiles);
reset();
setValue('publicationType', (e.target as HTMLButtonElement).value);
setActiveStep((prevStep: ActiveSteps) => prevStep + 1);
setValue('current', availableFiles[0].id);
setValue('next', availableFiles[0].id);
};
And then the getAvailableFiles function
const getAvailableFiles = async (type: 'privacy' | 'terms') => {
const data = await fetch(`/api/publications/manage/documents?type=${type}`);
const result = await data.json();
setAvailableFiles(await result);
setIsLoading(false);
console.log(availableFiles);
};
First time these run I get an empty array back, but the next time I load this component it fires.
It also does load the data into the availableFiles variable but at first it fires an empty array