Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
398 views
in Technique[技术] by (71.8m points)

reactjs - Alert not displaying when receiving json response

I am sending a bad request on purpose to try and proc an alert. I have tried many ways to do an alert, but this seems the most concise. However, none of what I have tried has worked. Can someone explain to me (as I am new to react native) how to make this alert show the response?

This is my code:

        const { name, username, email, password, device_name } = this.state;
        console.log(this.state)

        fetch('myURL', {
          method: 'POST',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            name: this.state.name,
            username: this.state.username,
            email: this.state.email,
            password: this.state.password,
            device_name: this.state.device_name
          })
        }).then((response) => response.json())
        .then((jsonResponse) => console.log(jsonResponse)).catch(error => {Alert.alert(error.status, jsonResponse[0])});
    };

here is the response data I am getting in the console log:

Object {
  "response": Object {
    "email": Array [
      "The email field is required.",
    ],
    "name": Array [
      "The name field is required.",
    ],
    "password": Array [
      "The password field is required.",
    ],
  },
  "status": "error",
}

Here is the code for the whole class:

import  React, {Component} from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import {View, Text, StyleSheet, TextInput, Button, Alert} from 'react-native';
import * as SecureStore from 'expo-secure-store';

export default class Registration extends Component {
    constructor(props) {
      super(props);
      
      this.state = {
        name: '',
        username: '',
        email: '',
        password: '',
        device_name: 'testDeviceID'
      };
    }

    submitRegistration = async () => {
        const { name, username, email, password, device_name } = this.state;
        console.log(this.state)

        fetch('myURL', {
          method: 'POST',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            name: this.state.name,
            username: this.state.username,
            email: this.state.email,
            password: this.state.password,
            device_name: this.state.device_name
          })
        }).then((response) => response.json())
        .then((jsonResponse) => console.log(jsonResponse)).catch(error => {Alert.alert(error.status, jsonResponse[0])});
    };

    render() {
        return (
            <View style={style.container}>
                <Text style={style.title} >Registration</Text>
                <TextInput 
                    style={style.input}
                    value={this.state.name}
                    placeholder="your name"
                    onChangeText={(name) => this.setState({ name })}
                />
                <TextInput 
                    style={style.input}
                    value={this.state.username}
                    placeholder="username"
                    onChangeText={(username) => this.setState({ username })}
                />
                <TextInput 
                    style={style.input} 
                    value={this.state.email}
                    placeholder="email"
                    onChangeText={(email) => this.setState({ email })}
                />
                <TextInput 
                    style={style.input} 
                    value={this.state.password}
                    placeholder="password"
                    autoCapitalize="none"
                    autoCorrect={false}
                    onChangeText={(password) => this.setState({ password })}
                />
                <Button title='Register' onPress={this.submitRegistration.bind(this)}/>
            </View>
        )
    };
};

const style = StyleSheet.create({
    container: {
        flex: 1,
        padding: 24,
        backgroundColor: "#eaeaea",
        marginTop: 24
    },
    title: {
        marginTop: 16,
        paddingVertical: 8,
        borderWidth: 4,
        borderColor: "#20232a",
        borderRadius: 6,
        backgroundColor: "#9bc2cf",
        color: "#20232e",
        textAlign: "center",
        fontSize: 30,
        fontWeight: "bold"
      },
      input: {
        marginTop: 16,
        paddingVertical: 8,
        borderWidth: 4,
        borderColor: "#20232a",
        borderRadius: 6,
        backgroundColor: "#61dafb",
        color: "#20232a",
        textAlign: "center",
        fontSize: 30,
        fontWeight: "bold"
      }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Seems your problem is on the promise. As the promise resolves just fine with the json data you are logging, the catch function is never called.

So options for you are:

  1. To throw an Error with the json attached when you receive an error response from backend.
.then((response) => response.json())
.then((jsonResponse) => { 
    if (response.status === "error") {
        let err = new Error(response.status);
        err.response = response;
    }
})
.catch(error => {Alert.alert(error.message, error.response)});
  1. To trigger the alert regardless of the result by using then instead of catch.
.then((response) => response.json())
.then(response => {Alert.alert(response.status, response)});

But you definitely need to read about promises to choose which solution to apply.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...