'How can I use a useDispatch and useSelector hook in a custom hook in react?
I've been trying to call the useDispatch hook and the useSelector hook in a custom hook but it always end up giving the error "Invalid hook call. Hooks can only be called inside of the body of a function component." Does this mean I cannot call it inside the custom hook?
import { useDispatch, useSelector } from 'react-redux'
import { getImage } from '../../redux/data'
import { useState } from 'react'
import { useDropzone } from 'react-dropzone'
export const useHandleEdit = data => {
const file = useSelector(state => state.imageData.data);
const user = useSelector(state => state.userData.data);
console.log("this handle edit function is working")
const output = {
...data,
file:() => {
if (file) {
return file
} else {
return user.photourl
}
}
}
console.log(output);
}
export const useOnDrop = () => {
const [image, setimage] = useState('')
const [file, setfile] = useState('')
const dispatch = useDispatch();
const onDrop = acceptedFile => {
const filePreview = acceptedFile.map(file =>
Object.assign(file, {
preview: URL.createObjectURL(file)
})
)
setfile(filePreview);
dispatch(getImage(file));
const image = filePreview.map(item => item.preview)
setimage(image)
}
const { getRootProps,getInputProps } = useDropzone({
accept: 'image/*',
multiple: false,
onDrop
})
return { getRootProps,getInputProps, image, file }
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
