0

I want to fetch my data from backend mongodb but the useeffect is rendering only once and at that moment data is not fetched quickly resulting in lots of undefined errors. Here is my code:

const [xnaLogData,setXnaLogData]=useState([]);
const [xnaLogMember,setXnaLogMember]=useState("");
const [balance,setBalance]=useState(0);
 
useEffect(() => {
    setXnaLogMember(Cookies.get('member_userr'));
    alert(xnaLogMember);
    const calBal = () => {
        var sum = xnaLogData.reduce(function(prev, current) {
            return prev + +current.balance
        }, 0);
        setBalance(sum);
    }

    const fetchXna = async () => {
        const response = await fetch('/xnaloginforoute');
        const json = await response.json();
        setXnaLogData(json.xnacomp);
        calBal();
        console.log(json.xnacomp)
        console.log(xnaLogData);
    }

    fetchXna();
},[]);

If i put },[xnaLogData]); inside the useeffect line },[]); it will start a continous chain of useeffect and the data is fetching in 3rd or 4th attempt of effect. I am unable to solve this issue

Jared Smith
  • 19,721
  • 5
  • 45
  • 83
Beren
  • 684
  • 2
  • 9
  • 14
  • The main problem you're having is that *React state updates are **not** synchronous*, they are batched for performance, and this is stated clearly in the documentation. So when you `setXnaLogData` and then call `calBal` which uses the state value it hasn't updated yet. Make `calBal` take a parameter that it reduces, and pass it `json.xnacomp`. – Jared Smith Sep 10 '21 at 20:34
  • Does this answer your question? [React setState not updating state](https://stackoverflow.com/questions/41446560/react-setstate-not-updating-state) – Jared Smith Sep 10 '21 at 20:35
  • I think the main problem is with useeffect because the useeffect is executed only once as i give it to empty [ ] but at that moment the api is not fetched . And why this api routes is getting too long to fetch while rest of the api's routes are working properly. Even though this api is working fine in POstman too but not at frontend – Beren Sep 10 '21 at 20:38
  • Do you have any idea about it? – Beren Sep 10 '21 at 20:40
  • Why are you telling me that you think I'm wrong about what the problem is but then asking for my opinion? Also, postman *is not a web browser*. It doesn't care about CORS or CSP or a lot of other things that browsers care about. It is a *very* limited tool for testing APIs meant to be consumed by a web browser. – Jared Smith Sep 10 '21 at 20:43

1 Answers1

2

Ok, this is a typical useEffect question.

Let's revisit your logic a bit.

  useEffect(() => {
    setAbc(value)
  }, [abc])

The problem of the above is an endless loop, unless the value can reach a stable value after couple of runs. Thus most of time, we have a short circuit line installed to break it off.

  useEffect(() => {
    if (count > 2) return
    setCount(v => v + 1)
  }, [count])

Either way i think you get the idea, either loop or not, it's entirely controlled by YOU, react is not going to make a decision what to do. You can rethink why you want to re-run the effect upon the value change.

windmaomao
  • 7,120
  • 2
  • 32
  • 36