I have a table in my database cold Apoet in my table field could name so I try to bring the name from the database but when I run the app this message appear
undefined is not an object (evaluating abc.name)
below my code
import React from 'react';
import {useEffect} from 'react';
import {useState} from 'react';
import { useRoute } from '@react-navigation/native';
import { DataStore } from 'aws-amplify';
import { Apoet } from '../../models';
const ProductScreen = () => {
const route = useRoute();
console.log(route);
const {abc, setABC}= useState<Apoet | undefined>(undefined);
useEffect (()=>{
if(!route.params?.id){
return ;
}
DataStore.query(Apoet,route.params.id).then(setABC)
},[route.params?.id]);
return (
<View>
<Text>{abc.name} </Text>
</View>
)}
CodePudding user response:
Your useState
is wrong, change with square brackets. Also be sure route
changes as you expect otherwise it will be undefined
again since your initial state value is also undefined
const [abc, setABC] = useState<Apoet | undefined>(undefined);
CodePudding user response:
Issues
You've incorrectly accessed the return value from the useState
hook, it returns an array, not an object.
const {abc, setABC} = useState<Apoet | undefined>(undefined);
You also use an undefined initial value, so attempting to access into it will throw an error.
Solution
Fix the return and use array destructuring assignment and use a valid initial value.
const [abc, setABC] = useState<Apoet>({});
...
<Text>{abc.name}</Text>
abc
is now defined and can access a name
property that will be undefined util the state is updated.
Or if you want to keep it allowed to be undefined, use a null check or Optional Chaining operator on the name
property access.
Example:
const [abc, setABC] = useState<Apoet | undefined>();
...
<Text>{abc && abc.name}</Text>
or
<Text>{abc?.name}</Text>