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

  Kiến thức lập trình

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.

LEAVE A COMMENT