Using react/redux toolkit
I have an item creation screen which uploads an image of the item and then creates an entry in my database for that item.
One of the database values is the imageURL, which should point to the recently uploaded image.
I have a stateful value for the imageURL and this should be changed to the correct path after the file has been uploaded but before dispatch of the creation of the database entry, but I can't get the imageURL to be set before the dispatch occurs.
I've tried useEffect as well as async but it imageURL seems to only be set after dispatch.
const [imageURL, setImageURL] = useState('');
//File upload handler
const uploadFileHandler = async (file) => {
const formData = new FormData();
formData.append('image', file);
setUploading(true);
try {
const config = {
headers: {
'Content-Type': 'multipart/form-data',
},
};
const fileURL = await axios.post('/api/upload', formData, config);
setUploading(false);
return fileURL.data; //this is the path of the uploaded file
} catch (error) {
console.error(error);
setUploading(false);
}
};
//TODO: Submit handler
const submitHandler = async (e) => {
e.preventDefault();
let path = await uploadFileHandler(uploadFile); //this should give me the URL from the upload
setImageURL(path); //this should set the Image URL to the above value, but does not
dispatch(createItem(data, headers));
};
If anyone knows how to fix this I would appreciate it.
Thanks
setImageURL? Is it auseStatesetter, or a redux action? If it's a redux action, is there any reason you aren't callingdispatchon it?const [imageURL, setImageURL] = useState('');