我正在尝试使用 reactrecoil
进行状态管理,到目前为止我很喜欢它,但是目前我正在尝试将它与之集成,但react-hook-form
我找不到适合我的设置。
很简单,我想执行一个函数,onSubmit
在完成一个Form
. 我已经设置了一个selector
来发出异步请求并更新一个atom
与上传进度相对应的,但是我在执行该函数时遇到了麻烦,因为它在回调而不是功能组件中被调用,我试图将它提取到一个自定义钩子,但这也无效;我已经提供了下面的代码,如果有人有任何想法,请告诉我!
当前实现的示例错误:
React Hook "useRecoilValue" is called in function "submit" which is neither a React function component or a custom React Hook function
代码:
export const videoUploadProgressState = atom({
key: "videoProgress",
default: {progress: 0.0}
});
export const videoUploadState = selectorFamily({
key: 'videoUploadState',
get: (data : {[key:string] : any}) => async ({get}) => {
const storage = get(firestoreStorageState);
const task = storage.ref(data.path).put(data.file);
const [progress, setProgress] = useRecoilState(videoUploadProgressState)
task.on("state_changed", snapshot =>{
switch(snapshot.state){
case 'running':
setProgress({progress: snapshot.bytesTransferred / snapshot.bytesTransferred});
break;
}
}
);
const response = await fetch(
"http://*********:80/streaming/create-video-asset",
{
method:'post',
body:JSON.stringify({url: (await task).ref.getDownloadURL()})
});
console.log(response.json());
return response.json();
}
})
const UploadMovieComponent = () => {
const [title, setTitle] = useState("Select movie");
const {register, handleSubmit} = useForm();
const movies = useRecoilValue(movieState);
const progress = useRecoilValue(videoUploadProgressState)
const submit = (data) => {
setTitle(
useRecoilValue(
videoUploadState(
{
path: `movies/${data.id}/${data.movieFile[0].name}`,
file: data.movieFile[0]
}
)
)
);
}
return(
<div>
<Form onSubmit={handleSubmit(submit)}>
<Form.Group controlId="exampleForm.SelectCustom">
<Form.Label>Select movie</Form.Label>
<Form.Control as="select" ref={register} name="id" custom>
{movies.map(movie=> <option value={movie.id}>{movie.title}</option>)}
</Form.Control>
</Form.Group>
<Form.Group>
<Form.File name="movieFile" ref={register}/>
</Form.Group>
<Button type="submit" variant="outline-warning">Upload</Button>
</Form>
<ProgressBar className="mt-2" now={progress.progress} />
</div>
);
}