Reputation: 33
I have a web application in react, and I have two registration page, one user and the next where you register a project, I need to get the user id that was registered on the previous page to register the project on the next page.
but I can't import the id because it's inside a function, so I can't get it
export default function Register({ history }) {
const [username, setUsername] = useState('');
const [email, setEmail] = useState('');
const [passwd, setPasswd] = useState('');
async function handleSubmit(e) {
e.preventDefault();
const response = await api.post('/createUser', {
username, email, passwd,
});
console.log(response.data);
const { _id: _idUser } = response.data;
history.push(`/freela/${_idUser}`);
}
I'm trying to import like this
import { _idUser } from './Register';
And he returns me this error:
Upvotes: 2
Views: 179
Reputation: 459
Quick suggestion: since you are pushing idUser
in history.push('/freela/${_idUser}
, you can probably extract _idUser
from the URL
Upvotes: 1
Reputation: 3690
I am taking that you are using react-router
or react-router-dom
for navigation.
For both the libraries you can pass some data as props for the next component like this in your case -
history.push(
/freela/${_idUser}, _idUser);
and in your next component you can access it by
props.location.state
But the best way is to get it from params since you have that id in your url.
By using the useParams
hook from react-router-dom
;
Link to an example - https://reacttraining.com/react-router/web/example/url-params
Upvotes: 1