In the variable const user inside useEffect
function, I get an user object, I want to use the id, firstname and lastname from the user object in textfield. Is it somehow possible to use the user object outside the useEffect
function?
In the code below the user object is undefined when used outside the useEffect
.
import React, { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { useLocation } from "react-router-dom";
interface userData {
id: number;
firstname: string;
lastname: string;
};
const [obj, setObj] = useState();
const location = useLocation<userData>();
useEffect(() => {
const user = allUsers.filter((obj) => obj.id === location.state.id);
// handling if user is undefined
if(user) {
console.log('Storing object data')
setObj(user);
} else {
console.log('No data!');
}
}, [location]);
return (
<div>
<h1>User Data</h1>
{/*Text field - id*/}
<TextField
name="id"
id="id"
label="ID"
value={obj.id}
fullWidth
/>
{/*Text field - firstname*/}
<TextField
name="firstname"
id="firstname"
label="First Name"
value={obj.firstname}
fullWidth
/>
{/*Text field - lastname*/}
<TextField
name="lastname"
id="lastname"
label="Last Name"
value={obj.lastname}
fullWidth
/>
</div>
);
In your code .filter()
returns an array. Probably you want to use .find()
instead. Also in either case I would update with setObj()
your state because you can handle null
in return
also with obj && obj.id
.
Try the following:
useEffect(() => {
const user = allUsers.find((obj) => obj.id === location.state.id);
setObj(user);
}, [location]);
Then in your return
:
return <div>
<h1>User Data</h1>
{/* Showing TextField only if obj is not null */}
{ obj && <TextField name="id"
id="id"
label="ID"
value={obj.id}
fullWidth />}
</div>
I hope this clarifies!