React Native Axios POST request throwing error: How to resolve in a mobile environment?

Certainly! In the React Native project I’m working on, I have a sign-up form component where I’m utilizing Axios to send a POST request to an API endpoint for user registration. Despite the functionality working flawlessly in the web environment, I’m facing a stumbling block when attempting to execute the same action in React Native. The error manifests specifically during the Axios call, throwing a “Network Error” despite my mobile device maintaining a stable internet connection. I’m seeking insights into why this discrepancy arises in a React Native context and how I can rectify it to ensure seamless API calls within the mobile environment.

import axios from 'axios';
import {
  Alert,
  ImageBackground,
  StyleSheet,
  Text,
  useColorScheme,
  View,
} from 'react-native';
import React, {useState} from 'react';
import {Button, Checkbox, TextInput} from 'react-native-paper';

export default function SignUp() {
  const scheme = useColorScheme();
  const image = {
    uri:
      scheme === 'dark'
        ? 'https://cdn.pixabay.com/photo/2023/10/17/02/14/lotus-8320293_640.jpg'
        : 'https://cdn.pixabay.com/photo/2024/02/10/15/03/graphic-8564947_640.png',
  };
  const [checked, setChecked] = useState(false);
  //   const [formData, setFormData] = useState({firstName: '', lastName: ''});
  const [formData, setFormData] = useState({
    firstName: '',
    lastName: '',
    email: '',
    roll: '',
    mobile: '',
    password: '',
    confirmPassword: '',
  });
  const [errors, setErrors] = useState(false);
  const [rollerrors, setRollErrors] = useState(false);
  const [emailerrors, setEmailErrors] = useState(false);
  const [passworderrors, setPasswordErrors] = useState(false);
  const [confirmPassworderrors, setConfirmPasswordErrors] = useState(false);

  const handleSubmit = async () => {
    const requestData = {
      // Convert data to JSON
      firstName: formData.firstName,
      lastName: formData.lastName,
      email: formData.email,
      roll: formData.roll,
      phone: formData.mobile,
      password: formData.password,
      confirmPassword: formData.confirmPassword,
    };
    console.log(requestData);
    try {
      const response = await axios.post(
        'http://localhost:8000/api/signUp',
        requestData,
      );

      const userData = response.data;

      console.log('User Data:', userData);
      // Handle user data as needed
    } catch (error) {
      console.error('Error:', error);
      // Handle error if needed
    }
  };

  return (
    <View style={styles.container}>
      <ImageBackground source={image} resizeMode="cover" style={styles.image}>
        <View style={styles.containerBox}>
          <TextInput
            style={styles.textField}
            mode="outlined"
            label="First Name"
            placeholder="Enter first name"
            onChangeText={text => setFormData({...formData, firstName: text})}
            value={formData.firstName}
            onBlur={() =>
              formData.firstName === '' ? setErrors(true) : setErrors(false)
            }
            error={errors}
          />
          <TextInput
            textContentType="username"
            style={styles.textField}
            clearButtonMode="always"
            mode="outlined"
            label="Last Name"
            placeholder="Enter last name"
            onChangeText={text => setFormData({...formData, lastName: text})}
            value={formData.lastName}
          />
          <TextInput
            textContentType="emailAddress"
            style={styles.textField}
            clearButtonMode="always"
            mode="outlined"
            label="Email"
            placeholder="Enter email address"
            onChangeText={text => setFormData({...formData, email: text})}
            value={formData.email}
            onBlur={() =>
              formData.firstName === ''
                ? setEmailErrors(true)
                : setEmailErrors(false)
            }
            error={emailerrors}
          />
          <TextInput
            textContentType="telephoneNumber"
            keyboardType="number-pad"
            style={styles.textField}
            clearButtonMode="always"
            mode="outlined"
            label="Mobile Number"
            placeholder="Enter mobile number"
            onChangeText={text => setFormData({...formData, mobile: text})}
            value={formData.mobile}
          />
          <TextInput
            style={styles.textField}
            clearButtonMode="always"
            mode="outlined"
            label="Roll. No."
            placeholder="Enter roll number"
            onChangeText={text => setFormData({...formData, roll: text})}
            value={formData.roll}
            onBlur={() =>
              formData.firstName === ''
                ? setRollErrors(true)
                : setRollErrors(false)
            }
            error={rollerrors}
          />
          <TextInput
            style={styles.textField}
            clearButtonMode="always"
            mode="outlined"
            label="Password"
            placeholder="Enter password"
            onChangeText={text => setFormData({...formData, password: text})}
            value={formData.password}
            textContentType="newPassword"
            onBlur={() =>
              formData.firstName === ''
                ? setPasswordErrors(true)
                : setPasswordErrors(false)
            }
            error={passworderrors}
          />
          <TextInput
            textContentType="password"
            style={styles.textField}
            clearButtonMode="always"
            mode="outlined"
            label="Confirm Password"
            placeholder="Confirm password"
            onChangeText={text =>
              setFormData({...formData, confirmPassword: text})
            }
            value={formData.confirmPassword}
            onBlur={() =>
              formData.firstName === ''
                ? setConfirmPasswordErrors(true)
                : setConfirmPasswordErrors(false)
            }
            error={confirmPassworderrors}
          />
          <View style={styles.policy}>
            <Checkbox
              status={checked ? 'checked' : 'unchecked'}
              onPress={() => {
                setChecked(!checked);
              }}
            />
            <Text>
              I aggree to policy*{' '}
              <Text
                style={{color: 'blue'}}
                onPress={() => console.log(formData)}>
                {/* onPress={() => openURL('https://www.google.com')}> */}
                policy
              </Text>
            </Text>
          </View>
          <Button
            disabled={!checked}
            mode="contained"
            onPress={handleSubmit}
            style={styles.button}>
            Sign Up
          </Button>
        </View>
      </ImageBackground>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  containerBox: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    gap: 10,
  },
  image: {
    flex: 1,
    justifyContent: 'center',
  },
  textField: {
    width: '85%',
  },
  button: {
    width: 150,
  },
  policy: {
    flexDirection: 'row',
    alignItems: 'center',
  },
});

In my attempts to resolve the issue, I’ve double-checked the network connectivity of my mobile device and verified the accessibility of the API endpoint from the device. Despite ensuring these prerequisites, I still encountered the “Network Error” when making the Axios POST request within React Native. Initially, I expected the API call to proceed smoothly, similar to its behavior in the web environment. However, the actual outcome deviated from my expectations, as the error persisted despite my efforts to troubleshoot.

New contributor

ADARSH RAJ is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật