1

I have a problem when I click my button.

This error only came up after I added

async (e) => {
e.preventDefault();

before adding that, it worked fine.

My App.js is:

import React from "react";
import Titles from "./components/Titles.js";
import Form from "./components/Form.js";
import Weather from "./components/Weather.js";

const API_KEY = "6726a7ca2675f6208f516878e6472f36";

class App extends React.Component {
  getWeather = async (e) => {
    e.preventDefault();
    const api_call = await fetch(`api.openweathermap.org/data/2.5/weather?q=London,uk&APPID=${API_KEY}`);
    const data = await api_call.json();
    console.log(data);
  }
  render() {
    return (
      <div>
        <Titles />
        <Form getWeather={this.getWeather}/>
        <Weather />
      </div>
    );
  }
}

export default App;

And my Form.js is:

import React from "react";

class Form extends React.Component {
    render() {
        return (
            <form onSubmit={this.props.getWeather}>
                <input type="text" name="city" placeholder="City..."/>
                <input type="text" name="Country" placeholder="Country..."/>
                <button>Get Weather</button>
            </form>
        );
    }
};

export default Form;

All I'm trying to do is log the returned API data when the button is clicked. So I need to stop the page refreshing when the button is clicked.

drandom3
  • 199
  • 1
  • 3
  • 13
  • 5
    `Unexpected token < in JSON at position 0` ***almost always*** means that you received HTML when you expected JSON (usually in the form of an error or 404 page). Check your console and look at the response. – Claies Nov 01 '18 at 02:22
  • Tested this: `const api_call = await fetch(`api.openweathermap.org/data/2.5/weather?q=London,uk&APPID=6726a7ca2675f6208f516878e6472f36`);` and response.ok is false – Dacre Denny Nov 01 '18 at 02:23
  • 1
    change `const data = await api_call.json();` to `const data = await api_call.text();` - then check what is logged in the console - also, `console.log(api_call.ok)` – Bravo Nov 01 '18 at 02:28
  • 1
    You have omitted the `https://` prefix from the URL. Without it, `fetch` will try and load `api.openweathermap.org...` as a relative resource. **Voting to close as a typo** – Phil Nov 01 '18 at 03:27
  • 1
    Thanks all. When I changed it to `api_call.text()` I got a weird HTML page about needing javascript. Once I added the `https://` I got the JSON I was after. – drandom3 Nov 02 '18 at 00:25
  • I was getting this querying a MongoDB collection. I checked the output window as @Claies suggested, and this led me to a more [specific solution](https://stackoverflow.com/q/11557912/197591). – Neo Aug 10 '19 at 18:53

0 Answers0