sekoyo / react-image-crop

A responsive image cropping tool for React
ISC License
3.77k stars 339 forks source link

Unable to Get `Value` in onSubmit Method #549

Open rahiyansafin opened 11 months ago

rahiyansafin commented 11 months ago

Description: I have a React component with the onSaveCrop function that is used to crop and upload an image. The onSaveCrop function uses a custom hook called useTrait to manage state. When I call onSaveCrop, I can see that bannerImageValue has the expected value inside the function, but when I try to use it in the onSubmit method, it always returns undefined.

Reproduction Steps:

Code Snippets:

`// useTrait.js import { useState } from "react";

export default function useTrait(initialValue) { const [trait, updateTrait] = useState(initialValue);

let current = trait;

const get = () => current;

const set = (newValue) => { current = newValue; updateTrait(newValue); return current; };

return { get, set, }; }

// The component code (partial) // ...

const companyCoverAsset = useTrait({});

const onSaveCrop = useCallback(async () => { // Image cropping and uploading logic here // ... const value = await handleCoverUpload( croppedImageFile, uploadURL, fileId, fileName );

if (value) companyCoverAsset.set(value); // Here, I can see that 'value' is not undefined.

console.log("value", value); console.log("companyCoverAsset.get()", companyCoverAsset.get()); // The value here is as expected.

// ... }, [...dependencies]);

const onSubmit = async (values) => { values.companyId = data?.data?.company?.id;

try { const bannerImageValue = await onSaveCrop(); // 'bannerImageValue' is always undefined here.

// ...

} catch (e) { console.log(e); // ... } }; `

Expected Behavior: I expect bannerImageValue to have the same value in the onSubmit method as it does inside the onSaveCrop function.

Additional Notes: I have verified that the onSaveCrop function correctly sets the value obtained from handleCoverUpload using the companyCoverAsset.set(value) call. However, when accessing bannerImageValue in the onSubmit method, it seems to lose the updated value and remains undefined. I suspect that there might be an issue related to the lifecycle or timing of the custom hook's state update.