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 on

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

cleper profile image

Sorry, i'm just myself used react and axios once, so i might be no help, but i suggest that you should not render error itself on page(line 57) but console log it first to see exact error abd then handle it, for example you can tell that api have no information about provided inputs. Sorri if it doesn't help as i said i'm pretty new to programming myself.

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.