Search code examples
react-nativereact-hooksuse-effect

POST METHOD: Error: Invalid hook call. Hooks can only be called inside of the body of a function component


I would like to alert a message from the API when a TouchableOpacity is pressed. I have a single function handling seatBooking and individual functions calling seatBooking function for a message. Here is my code

const generalBooking = (seat, uid, vid, tc_id) => {
    const [msg, setMsg] = useState(0);
    useEffect(() => {
      (async () => {
        const response = await fetch(
          `http://192.168.8.100/dbops/actions/make_booking.php?seat=${seat}&uid=${uid}&vid=${vid}&tc_id=${tc_id}`
        );
        const result = await response.json();
        setMsg(result.message);
        // alert(result.message);
      })();
    }, []);

    return msg;
  };

function seat1Booking(seat1, uid, vid, tc_id) {
    const msg = generalBooking(1, uid, vid, tc_id);
    Alert.alert(msg);
  }

return (
    <Screen style={{ paddingBottom: 5 }}>
          {/* Seat 1 starts */}
          <TouchableOpacity style={styles.seat} onPress={seat1Booking}>
            <MaterialCommunityIcons name="seat" size={40} color={seat1Color} />
            <Button title="1" style={{ width: 20 }} color={seat1Color} />
          </TouchableOpacity>
          {/* Seat 1 ends */}
    </Screen>
)

The generalBooking and individual seat1Booking function work ok when I log it outside console.log(seat1booking()) but when I passed it to the TouchableOpacity, it gives a warning

1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
....

I have tried reading a number of links Error Invalid hook call. Hooks can only be called inside of the body of a function component, How to fix React(TypeScrtipt) error "Invalid hook call."? including the link provided in the error message all in vain.

could the problem be function calling on individual functions handling seat booking e.g seat1Booking or it is the generalBooking function? Please advise


Solution

  • I managed to get a solution to this question and here it is,

    const generalBooking = async (seat, uid, vid, tc_id) => {
        // const [msg, setMsg] = useState(0);
        const response = await fetch(
          `http://192.168.8.100/dbops/actions/make_booking.php?seat=${seat}&uid=${uid}&vid=${vid}&tc_id=${tc_id}`
        );
        const result = await response.json();
        // setMsg(result.message);
        Alert.alert("Booking Status", result.message);
      };
    
      useEffect(() => {
        return () => {
          seatBooking(seat, uid, vid, tc_id);
        };
      }, []);
    
    const seat1Booking = (seat, uid, vid, tc_id) => {
        seatBooking(1, uid, vid, tc_id);
      };
    

    Thank you @Hazout for the hint as it guided my search.