Home > Blockchain >  Why am I getting undefined from a string that has data?
Why am I getting undefined from a string that has data?

Time:03-21

So I am pulling data from my database using an API with this code:

let { id } = useParams();
const [Tenant, setTenant] = useState("");
useEffect(() => {
  axios.get(`http://localhost:3001/tenants/byId/${id}`).then((response) => {
    setTenant(response.data);
  });
}, []);

I then try to set a default value on my Material UI textfield using:

<TextField 
    required id="Field1" 
    defaultValue={Tenant.tenantName}
    label="Tenant Name" 
    variant="outlined" 
    onChange={(event) => {setNtenantName(event.target.value)}}
    />

But, I was not getting anything. So I decided to console.log(Tenant.tenantName) and was getting this in my console:

Console Log

CodePudding user response:

Your state is not ready by the time you're trying to access it.

So you can check for it.

{Tenant && (
   <TextField 
        required id="Field1" 
        defaultValue={Tenant.tenantName}
        label="Tenant Name" 
        variant="outlined" 
        onChange={(event) => {setNtenantName(event.target.value)}}
        />
)}

also on a side note it's not common to capitalize your state names.

u can change it to : const [tenant, setTenant] = useState(""); just for convention

CodePudding user response:

What Kevin is proposing should work well, but you can also do something like so, which it might be easier to read and will display a loader while is fetching the data..

if(Tenant === undefined) return <div>Loading data....</div> 
else return (
  <TextField 
    required id="Field1" 
    defaultValue={Tenant.tenantName}
    label="Tenant Name" 
    variant="outlined" 
    onChange={(event) => {setNtenantName(event.target.value)}}
    />
)

CodePudding user response:

So why not try console.log(Tenant) before you console.log?

  • Related