DEV Community


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) => {
    const URL = ''
    const API_KEY = "8b46d478a9...34a69";
    const country =;
    const city =;
    try {
      if (country && city) {
        const response = await 
        const data = await response;
          error: '',
      } else {
          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 && && {
      showResult =
          <li>Location: {} {}</li>
          <li>Current Temperature: {this.state.currentTemp}° Celsius</li>
    else {
      showResult = <div className="error">

    return (
        <Form onGetWeather={this.getWeather} />

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.

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:

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)

klvenky profile image
Venkatesh KL • Edited

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

syedmuneebbukhari profile image

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.