I was following this video ("JWTUser Sessions with ReactJS & GraphQL...") when at this time the guy destructures useParams()
method from react-router-dom library.
In my case, that didn't work since I am getting this error:
This is the whole code at this point:
import React, { useState, useContext } from 'react';
import { useParams, useHistory } from 'react-router-dom';
import { useConfirmMutation } from '../gql/generated/graphql';
import { AppStateContext } from './provider';
export const Confirm: React.FC = () => {
const history = useHistory();
const { appSetAuthToken, appClearAuthToken, gqlError } = useContext(AppStateContext);
const [show, setShow] = useState(false);
const [email, setEmail] = useState('');
const [confirm] = useConfirmMutation();
const { token } = useParams();
const handleFormSubmit = async (e: React.FormEvent) => {
e.preventDefault();
try {
setShow(false);
appSetAuthToken(token);
const { data } = await confirm({ variables: email });
} catch {
}
};
if (token === undefined || token === '')
return <div>Enlace de confirmación de usuario inválido</div>;
return (
<div>
<div>Página de confirmación de usuario</div>
{show ? <div>{gqlError.msg}</div> : undefined}
<form>
<div>
<input
value={email}
placeholder='Correo electrónico'
type='email'
onChange={e => { setEmail(e.target.value); }}
/>
</div>
<button type='submit'>Confirmar</button>
</form>
</div>
);
};
I have also tried the same on CodeSandbox but it works. Not sure, where is my mistake. Can you see that mistake?
In order to useParams you need to implement a generic for useParams. Building on my example above, I need to type the id . type QuizParams = { id: string; }; // In order to implement that, I'd apply my type to the hook when calling it. const { id } = useParams<QuizParams>();
Step 1: Create a React application using the following command. Step 2: After creating your project folder i.e. useparams_react, move to it using the following command. Step 3: After creating the ReactJS application, Install the react-router-dom and react-dom packages using the following command.
useParams
is generic. You need to tell typescript which params you are using by specifying the value of the generic like this: useParams<MyParams>()
; In your case it is:
const { token } = useParams<{token?: string}>();
Which says that token
is either a string
or undefined
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With