I am creating a form using Formik. I have created my form following the pattern here: https://formik.org/docs/examples/basic
Now I want to use the result of the useParams react hook (https://reach.tech/router/api/useParams) as an input to the onSubmit function.
This is the onSubmit part from the Formik docs:
onSubmit={async (values) => {
await new Promise((r) => setTimeout(r, 500));
alert(JSON.stringify(values, null, 2));
}}
I tried adding this line:
onSubmit={async (values) => {
await new Promise((r) => setTimeout(r, 500));
const myValue = useParams()["myParam"]
alert(JSON.stringify(values, null, 2));
}}
where useParams
is imported from 'react-router-dom'
But this gives me an error:
React Hook "useParams" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function
I am new to React/Formik and don't know how to proceed from here. How can I get the value of myParam
inside the onSubmit function?
CodePudding user response:
As the error mentioned, you should call useParams()
on the component level instead of in the callbacks (or non-components).
You can check the example in this document again
import { useParams } from "@reach/router"
// route: /user/:userName
const User = () => {
const params = useParams(); //on the top of `User` component
return <h1>{params.userName}</h1> //SHOULD NOT CALL `useParams` IN ANY CALLBACKS HERE
)
According to your code, the correct way should be
//I assume that `onSubmit` is in `Form` component
const Form = () => {
const { myParam } = useParams() //you should call your `useParams` on the component level
return <button onSubmit={async (values) => {
await new Promise((r) => setTimeout(r, 500));
const myValue = myParam //replace for `useParams`
alert(JSON.stringify(values, null, 2));
}}>
}
CodePudding user response:
React Hooks are particular functions that React uses to perform React logic, you can spot them in a React project since they are named with use prefix : useNameOfHook
React hooks can be invoked only inside the body of a React component, so they can't be nested inside another function as you are trying to do. (Check the "Rules of hooks" to find out more about hooks in React").
useParams
is a React Router hook which returns you route params, so you just need to call it inside your React component, like this:// App.js const App = () => { const params = useParams() console.log("PARAMS", params) return (<div>{params.yourParam}</div>) }