400 Bad Resquest Error in React Native with Axios

Asked

Viewed 485 times

0

I made this code based on a React project. Using Axios and React Native, I am trying to return the data from the array, but it is only returning in the log an error 400 in the request of the api.

Here is the code:

main.js

import React, {Component} from 'react';
import Weather from '../services/weather';
import axios from 'axios';
import{ View, Text, TextInput, Button } from 'react-native';

export default class Main extends Component {

    static navigationOptions = {
        title: "Open Weather"
    }

    constructor() {
        super();
        this.state = {
          weather: [],
          temp: [],
          clouds: []
        }
    }

    getWeather = query => {
        axios.get(`https://api.openweathermap.org/data/2.5/find?q=${query}&units=metric&appid=6724e5bbc20ecbdb04109535892e5e49`)
          .then(response => {
            this.setState({
              weather: response.data.list[0],
              temp: response.data.list[0].main.temp,
              clouds: response.data.list[0].weather[0].description
            });
          })
          .catch(error => {
            console.log('Error', error);
          });
      };

    queryWeather = (event, cityName) => {
            event.preventDefault();
            cityName = event.target.value;
            this.getWeather(cityName);            
    }


    render(){
        return(
            <View>
                <Text>Cidade: </Text>
                <TextInput queryWeather={this.queryWeather} 
                    style={{ height: 40, borderColor: '#dfdfdf', borderWidth: 1 }} 
                    placeholder={'Digite o nome da cidade...'}                    
                />
                <Button title="Buscar" onPress={this.queryWeather}/>
                <Weather
                    city={this.state.weather.name}
                    temp={this.state.temp}
                    clouds={this.state.clouds} 
                />
            </View>
        );
    }
}

Weather.js

import React from 'react';

import { Text, View } from 'react-native';

const Weather = props =>

    <View>
        <Text>Cidade: {props.city}</Text>
        <Text>Temperatura: {props.temp}</Text>
        <Text>Céu: {props.clouds}</Text>
    </View>

export default Weather;

1 answer

0

To begin with, I would say that your code is messed up, in a way its functions are wrong since when clicking the button is called a function that will take the value of the input and then call the function to perform the request, it is unnecessary to perform this whole process. After all, the variable query that arrives at the function that will make the request has the value of undefined causing 400 error that is shown. Demo here

Instead of having the "queryWeather" function that takes the input value, I think it’s the best way, you can use a state and assign the keyboard input to that state. Your TextInput shall be as follows::

<TextInput 
    style={{ height: 40, borderColor: '#dfdfdf', borderWidth: 1 }} 
    placeholder={'Digite o nome da cidade...'}  
    onChangeText={(search) => { this.setState({ search }) }} 
    // O estado search alterado acima deve ser préviamente criado
/>

Finally, we call directly the function "getWeather" and not "queryWeather", and as you have in the state search the value the user entered, just add the this.state.search in the url to perform the request, being as follows:

getWeather = () => {
    axios.get("https://api.openweathermap.org/data/2.5/find?q="+this.state.search+"&units=metric&appid=6724e5bbc20ecbdb04109535892e5e49")
      .then(response => {
        console.log(response);
        this.setState({
          weather: response.data.list[0],
          temp: response.data.list[0].main.temp,
          clouds: response.data.list[0].weather[0].description
        });
      })
      .catch(error => {
        console.log('Error', error);
      });
  };

You have here all the code working. Some tips:

  • Always search for the methods of a component (Textinput -> Onchangetext), in most cases there will be one appropriate for your case (Use documentation).
  • Use the logs (console.log(var)), so it’ll be easier to see what’s wrong with your code.
  • Keep code simple and always be objective.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.