I've been trying to solve a problem for 4 days and I've searched and searched a lot! I'm not sure if I'm just searching for the wrong thing or seeing it and am just completely oblivious to it. My problem is that when I call the hook from the main function, it works, but when I call it via an onSubmit function, it fails for invalid hook call. I understand the concept of why the hook would be invalid, but am just completely unsure how to resolve it. I reformatted my hook so that I could initialize it earlier in my code and then call it via the onSubmit, but the problem is that the state token only gets updated on initialization and not whenever it's changed. Thus leading to some API calls with a bad token. Any Help Anyone can offer will be greatly appreciated!
The Setup: NextJS, React-Form, Redux via Next-Redux-Wrapper, SWR
When ReactForm validates the form, I'd like for it to submit it's data to a custom hook. However, that custom hook fails with the Invalid Hook Call. It does it as soon as I defined a variable for useState.
-- Form Code ---
const { register, errors, handleSubmit, setValue, reset, control } = useForm()
<form onSubmit={ handleSubmit(onSubmit) }>
-- onSubmit Code ---
const onSubmit = (data) => {
const newData = useApiPost(`users/update/${ id }`, submitData)
}
-- Custom Hook --
function useApiPut(resource, params){
const [ data, setData ] = useState(null)
const [ error, setError ] = useState(null)
const { url, data : inData } = rest(resource, params)
//Post data
const { data : resData, error : resError, mutate } = useSWR(
state.user.token ? url : null,
url => axios.request({
url,
method : 'post',
data : inData,
headers : { Authorization : `Bearer ${ state.user.token }` }
})
.then(({ data }) => data),
{ revalidateOnFocus : false }
)
useEffect(() => {
if(resData) {
setData(resData)
}
if(resError) {
setError(resError)
}
}, [ resData, resError ])
return { data, error, mutate }
}