Home > Mobile >  Cannot read property 'NaN' of undefined react js
Cannot read property 'NaN' of undefined react js

Time:09-19

i keep geeting the error "Cannot read property 'NaN' of undefined" i think the .length is causing the problem cause i think the length is sometimes undefind and that's causing the NaN problem however i'm not sure how to fix this. this is my code

  const getApiData = async () => {
   setIsLoading(true);
  const response = await fetch(
    `https://api/find_similar?id=${_id}`      
  ).then((response) => response.json());
  setIsLoading(false);

  // update the state
  setData(response);
};

useEffect(() => {
getApiData();
// eslint-disable-next-line
}, []);

// this line is causing the problem
const preSaving = data[data?.length - 1].price - data[0].price
const saving = Math.round((preSaving   Number.EPSILON) * 100) / 100
// this line is causing the problem
const prePercentageSaving = ((1 - ( data[0].price / data[data?.length - 1].price )) *100)
const percentageSaving = Math.round((prePercentageSaving   Number.EPSILON) * 100) / 100

}

CodePudding user response:

So if data is undefined, then in the line data[data?.length - 1].price - data[0].price the following happens:
data?.length // undefined
data?.length - 1 // NaN
data[data.length - 1] // Uncaught Type Error

You could try initializing data as an empty array, which won't solve all problems but is probably a good idea anyways. Then data[data.length - 1] becomes undefined (no Element exists in the array). Therefore you will still run into a problem with data[data.length - 1].price. Basically you are trying to do computations on data you don't have.

So make sure to only do the computations once you have the data, e.g. move them into the setData function.
Alternativly check, if data exists and set them to a good default otherwise, e.g.
const preSaving = data ? data[data?.length - 1].price - data[0].price : 0

CodePudding user response:

i think this would fix it:

replace this

data[data?.length - 1].price

with

data[data?.length - 1]?.price

CodePudding user response:

You should check if the array is initialized first before accessing anything inside of it which leads to the error you are recieving. Try this :

const preSaving = data.length ? data[data.length - 1].price - data[0].price : null;

CodePudding user response:

I tried opening the link that was being fetched without the id filter

https://api/find_similar

But my browser said it couldn't find the page.

Also, when I'm fetching data, I like to set it to an empty useState first

const [myApi, setMyApi] = useState(null)

And then, within the useEffect, set the data to that API

useEffect(() => {
  fetch(url).then(response => {return response.json()}).then(data => {setMyApi(data)})
}, []) 
  • Related