Home > Enterprise >  undefined is not an object (evaluating pray.findIndex)
undefined is not an object (evaluating pray.findIndex)

Time:08-28

when i run the code i get this error,

undefined is not an object (evaluating 'pray.findIndex')]

const [pray, setPray] = useState([]);
const fetchPray = async county => {
 const url4 = '-'   county;
 console.log(url4);
 fetch(url4)
.then(response => response.json())
.then(json => setPray(json))
.then(pray => {
  let index = pray.findIndex(d => d.MiladiTarihKisa === date);
  let selectData = pray[index];

  setVakitGunes(selectData.Gunes);
  setVakitImsak(selectData.Imsak);
  setVakitOgle(selectData.Ogle);
  setVakitIkindi(selectData.Ikindi);
  setVakitAksam(selectData.Aksam);
  setVakitYatsi(selectData.Yatsi);
  setGunTurkce(selectData.MiladiTarihUzun);
})
.catch(error => console.log(error))
.finally(() => setLoading4(false));
};

CodePudding user response:

The issue is due to .then(json => setPray(json)) line. It is an equivalent to

.then(json => {
  const res = setPray(json);
  return res;
})

And setPray or any other setter-function from useState returns undefined (void). So the next .then just after it will get undefined instead of what you were expecting.

Fix:

const fetchPray = async (county) => {
  const url4 = "-"   county;
  console.log(url4);
  fetch(url4)
    .then((response) => response.json())
    .then((pray) => {
      setPray(pray);
      let index = pray.findIndex((d) => d.MiladiTarihKisa === date);
      let selectData = pray[index];

      setVakitGunes(selectData.Gunes);
      setVakitImsak(selectData.Imsak);
      setVakitOgle(selectData.Ogle);
      setVakitIkindi(selectData.Ikindi);
      setVakitAksam(selectData.Aksam);
      setVakitYatsi(selectData.Yatsi);
      setGunTurkce(selectData.MiladiTarihUzun);
    })
    .catch((error) => console.log(error))
    .finally(() => setLoading4(false));
};
  • Related