I have a simple react app like
const [shoe, setShoe] = useState('')
formSubmit = () => {
e.preventDefault()
const { data } = useQuery<GetShoeDetailsQuery,GetShoeDetailsQueryVariables>(getShoeDetailsQuery, {
variables: {
name: String(shoe),
},
})
console.log(data)
}
<form onSubmit={formSubmit}>
<input type="text"
onChange: (e: { target: { value: SetStateAction<string> } }) => {
setShoe(e.target.value)
},
>
<button></button>
</form>
so when the form is submitted it makes a graphql call
my problem is I get an error react-dom.development.js:14906 Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for on
How can I call the useQuery after the form is submitted.
2 Answers
Not sure what library you are using to work with GraphQL. If it is from apollo: Use useLazyQuery
instead of useQuery
https://www.apollographql.com/docs/react/api/react/hooks/#uselazyquery
You can use refetch
of useQuery.
const [shoe, setShoe] = useState('')
const { data, refetch } = useQuery(getShoeDetailsQuery, {
variables: {
name: String(shoe),
},
})
formSubmit = () => {
e.preventDefault()
refetch();
}
<form onSubmit={formSubmit}>
<input type="text"
onChange: (e => {
setShoe(e.target.value)
},
>
<button></button>
</form>
In this case, the data will be fetched automatically when shoe
changes.
You can disable this query from automatically running by setting skip
: true.
const { data, refetch } = useQuery(getShoeDetailsQuery, {
variables: {
name: String(shoe),
},
skip: true,
})