DEV Community

Kayut
Kayut

Posted on

React and Axios - How to avoid 404 error

I'm trying to write my very first React application.
In a form with two input fields, the user type the name of a country and a city inside the input fields and submit the form.
city and country variables are then passed to the following component, which should send an API-Request to openweatehrmap API and show the results.

import React, { Component } from 'react';
import axios from 'axios';
import Form from './Form/Form';

class Weather extends Component {
  state = {
    country: '',
    city: '',
    currentTemp: '',
    error: undefined,
  }


  getWeather = async (e) => {
    e.preventDefault();
    const URL = 'http://api.openweathermap.org/data/2.5/weather?q='
    const API_KEY = "8b46d478a9...34a69";
    const country = e.target.elements.country.value;
    const city = e.target.elements.city.value;
    try {
      if (country && city) {
        const response = await 
axios.get(`${URL}${city},${country}&appid=${API_KEY}&units=metric`);
        const data = await response;
        console.log(data);
        this.setState({
          country: data.data.sys.country,
          city: data.data.name,
          currentTemp: data.data.main.temp,
          error: '',
        });
      } else {
        this.setState({
          country: undefined,
          city: undefined,
          currentTemp: undefined,
          error: 'Please enter a country and a city name'
        })
      }
    } catch (err) {
      this.setState({ error: err })
    }
  }


  render() {
    let showResult;
    if (this.state.error !== undefined && this.state.country && this.state.city) {
      showResult =
        <ul>
          <li>Location: {this.state.country} {this.state.city}</li>
          <li>Current Temperature: {this.state.currentTemp}° Celsius</li>
        </ul>
    }
    else {
      showResult = <div className="error">
        {this.state.error}
      </div>
    }

    return (
      <div>
        <Form onGetWeather={this.getWeather} />
        {showResult}
      </div>
    );
  }
}

export default Weather;

If you let one or both input fields empty and submit the form, the UI shows an error.
If you fill in both input fields and the country and the city are related (for example UK and London), the UI shows the temperature and some other info.

However,
If you fill in both input fields with just some random text, or if the country and the city are not related to each other, the App crashes as soon as the form is submitted.

I think this is because that the generated API-URL isn't valid any more. The console shows the following error:

https://thepracticaldev.s3.amazonaws.com/i/zo4rzpflnai896424gq4.png

I spent a whole day, but I couldn't find a way to fix it. How can I avoid the app from crashing. How can I validate the generated API-URL? Or any other hint or solution?

Top comments (3)

Collapse
 
klvenky profile image
Venkatesh KL • Edited

Because error that is throwm by axios is an Obiect. You should try stringify the error

Collapse
 
syedmuneebbukhari profile image
SYEDMUNEEBBUKHARI • Edited

in form where you call function call execute it with arrow function ()=>this.func

Some comments may only be visible to logged-in visitors. Sign in to view all comments.