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')]

thx for help

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 useState hook returns:

  1. The state value (in your case pray)
  2. The function to change that value (in your case setPray)

setPray can be given either a callback returning the new value for pray or just the new value for pray and returns void.

So in your code:

const [pray, setPray] = useState([]);

...

    .then(json => setPray(json)) // 'setPray' returns void here
    .then(pray => {              // 'pray' is always undefined, since void isn't a value
        ...
    });

CodePudding user response:

Just a thought, what if you set the default state to an empty object instead of an array:

const [pray, setPray] = useState({});

If that doesn't work, can you provide the entire file or link to dig deeper? I also think @MrCodingB is on the right track... here is an example of using useState with the function (setCount in example, setPray for you) returning something (count 1)

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count   1)}>
        Click me
      </button>
    </div>
  );
}

Good luck!

  • Related