Home > Blockchain >  React Native undefined is not an object while fetching data
React Native undefined is not an object while fetching data

Time:12-30

I want to print a document that uses data that I need to fetch first but it always gets 'undefined is not an object (evaluating 'items.username')' error since the items are still in the fetch state while the HTML variable is created

here's an example of my code

const [items, setItems] = React.useState();
const [loading, setLoading] = React.useState(true)

const getData = async () => {
   const response = await axiosInstance.get(`/userData/get`)
   if (response?.data?.success) {
     const result = response.data?.result[0] || [];
     setItems(result);
   }
}

React.useEffect(() => {
   (async () => {
      setLoading(true);
      try {
        await getData();
      } catch (err) {
         Alert.alert("", err?.response?.data?.message || err?.message);
      }
      setLoading(false);
    })();
}, []);

const userHTML = `<h1>${items.username}</h1>`

const printHTML = async () => {
   await Print.printAsync({
      userHTML,
   });
};

is there a way to delay the userHTML creation so it will be generated after the fetching is done or maybe there is a best practice to do this kind of thing?

note: the print function will be on the same page as where the userData is being fetched since the data always changed so it will not be possible to fetch data and store it first then move to the page with the print function

CodePudding user response:

You can set the useHTML like this:

const userHTML = `<h1>${!!items ? items.username : ''}</h1>`
  • Related