skip to Main Content

I am writing my first Expo/React-Native(-Express-Mongoose) App and after the 5th clicks my Android Expo App freezes.(i cant click anymore, doesnt response). I have no error and I have no idea, what am I doing wrong.

import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View, Button, Image, Pressable } from 'react-native';
import { useState, useEffect, useCallback } from 'react';


export default function App() {

  const [click, setClick] = useState({ frage: "serviceallgemein", like: "", datum: "" });
  const [savebar, setSave] = useState({ savebar: false });
  const [thankyou, setthankyou] = useState({ thankyou: false });

  const handleClick4 = () => {
    setClick((prev) => ({
      ...click,
      like: 4,
      datum: new Date().toLocaleString(),
    }
    ))
    setSave((prev) => ({ savebar: true }))
  }
  const handleClick3 = () => {
    setClick((prev) => ({
      ...click,
      like: 3,
      datum: new Date().toLocaleString(),
    })
    )
    setSave((prev) => ({ savebar: true }))
  }
  const handleClick2 = () => {
    setClick((prev) => ({
      ...click,
      like: 2,
      datum: new Date().toLocaleString(),
    })
    )
    setSave((prev) => ({ savebar: true }))
  }
  const handleClick1 = () => {
    setClick((prev) => ({
      ...click,
      like: 1,
      datum: new Date().toLocaleString(),
    })
    )
    setSave((prev) => ({ savebar: true }))
  }

  const setAlarm = () => {
    setSave((prev) => ({ savebar: false }));
    setthankyou((prev) => ({ thankyou: true }));
  }





  useEffect(() => {
    //check if data already saved (megnezi hogy volt e mar az adat mentve(ha igen, akkor az ertek false lesz, kattintasra true)rerender eseten)
    if (savebar.savebar === true) {
      //if initiation-no save-megnezi hogy nem e inicializalo rendering e
      if (click.like != "") {
        //node connection?-megnezi hogy el a node kapcsolat
        const checkfetch = async () => await fetch('http://192.168.2.165:9000/like');
        checkfetch().then(res => res.text())
          .then(res => {
            if (res == "nodeisok") {
              const fetching = async () => await fetch('http://192.168.2.165:9000/like', {
                method: 'POST',
                headers: {
                  'Content-Type': 'application/json'
                },
                body: JSON.stringify({ frage: click.frage, like: click.like, datum: click.datum }),
              });
              fetching().then(
                setAlarm())
                .catch((error) => {
                  alert("No connection");
                })


            }
          }).catch((error) => {
            alert("No connection");
          });
      }
    }
    const setstatethankyou = () => { setthankyou((prev) => ({ thankyou: false })) };
    const timer = setTimeout(() => setstatethankyou(), 4000);
    return () => { clearTimeout(timer) }
  }
    , [click]
  )
  /* */
  return (<View style={styles.container}>
    {thankyou.thankyou == true ?
      <View style={styles.containerthankyou}>
        <Text style={styles.thankyou}>Vielen Dank!</Text>
      </View>
      :
      <View style={styles.containernormal}>
        <Text style={styles.frage}>Wie gefällt Ihnen unsere Service?</Text>
        <View style={styles.buttonbox}>
          <Pressable style={styles.buttons} onPress={handleClick4}><Text style={styles.smiley} >😍</Text></Pressable>
          <Pressable style={styles.buttons} onPress={handleClick3}><Text style={styles.smiley} >🙂</Text></Pressable>
          <Pressable style={styles.buttons} onPress={handleClick2}><Text style={styles.smiley} >😐</Text></Pressable>
          <Pressable style={styles.buttons} onPress={handleClick1}><Text style={styles.smiley} >☹️</Text></Pressable></View>
        <StatusBar style="auto" />
      </View>}

  </View >
  );
}

const styles = StyleSheet.create({
 ...

I have tried to delete the timer-thankyou segment to check if setTimeout was wrong- no changes

2

Answers


  1. Chosen as BEST ANSWER

    My bug was in backend.

    app.post('/send', function (req, res, next) {
    var getfrage = req.body.frage;
    var getlike = req.body.like;
    //"2015-01-01T23:02"
    var getdatum = req.body.datum;
    var obj = { frage: getfrage, like: getlike, datum: getdatum };
    createLike(obj);
    res.end(); <---- This is what I forgot.
    

    });

    My fetch started every time and doesnt end. I dont understand why, but after the 5th clicks i couldnt connect anymore.


  2. It’s hard to track what’s happening because some of the code is written in a confusing way. For instance, you’re mixing the async/await pattern with the .then pattern, you should choose one or the other.

    Async/await

    const statusResponse = await fetch('http://192.168.2.165:9000/like');
    const statusText = await res.text();
    if (res == "nodeisok") {
      try {
        const saveResponse = await fetch('http://192.168.2.165:9000/like', {...etc});
        setAlarm();
      } catch(error) {
        alert("No connection")
      }
    }
    

    .then

    const checkfetch = fetch('http://192.168.2.165:9000/like')
      .then(res => res.text())
      .then(res => {
        if (res == "nodeisok") {
          const fetching = fetch('http://192.168.2.165:9000/like', {...etc});
            .then(() => setAlarm())
            .catch((error) => alert("No connection"))
                }
              }).catch((error) => alert("No connection"));
        }
      }).catch((error) => alert("No connection"));
    

    Another general suggestion is to use more specific state types, rather than objects with multiple properties. For instance, you could have const [saveBarVisible, setSaveBarVisible] = useState(false); and const [rating, setRating] = useState(-1);.

    The real problem, as I see it, is that your code is more confusing than it needs to be and this makes it hard to find what the real problem and solution is. That said, if I had to guess, I would say the error is that setAlarm is not being called reliably, and so saveBar is false and it doesn’t do anything.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search