0

enter image description hereI'm trying to take the form values and pass them into an API call, but the variable ${city} is being treated as a string. I've looked at various other examples of variable usage within a fetch call and this does seem proper. What am I doing wrong?

The function:

class App extends Component {
  getWeather = async (e) => {
    const api_key = '11deac5d16f942afda257188d880da59';
    e.preventDefault(); 
    const city = e.target.elements.city.value;
    const country = e.target.elements.country.value;

    const call = await fetch('http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&appid=11deac5d16f942afda257188d880da59');
    const data = await call.json();

    console.log(data);
    }

The Form:

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>Fetch Weather</button>   </form>
);
}
};

export default Form;
CodeSpent
  • 1,684
  • 4
  • 23
  • 46
  • 1
    Instead of single quotes use backticks (escapade here) `\`My name is${name}\``. Also check if your [fetch call](https://stackoverflow.com/questions/5226311/installing-specific-package-versions-with-pip) is correct – trinaldi Jul 01 '18 at 02:46
  • @Tico used insomnia to verify the call. Changed to backticks and worked perfectly, thank you. – CodeSpent Jul 01 '18 at 02:49
  • 1
    Haha it happens, glad I could help – trinaldi Jul 01 '18 at 02:51

2 Answers2

1

You need to use backticks

`http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&appid=11deac5d16f942afda257188d880da59`

vs what you have:

'http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&appid=11deac5d16f942afda257188d880da59'
imjared
  • 19,492
  • 4
  • 49
  • 72
1

String interpolation in ES6 should be used with backticks. ``.

In your case, change this line:

const call = await fetch('http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&appid=11deac5d16f942afda257188d880da59');

to

const call = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&appid=11deac5d16f942afda257188d880da59`);
trinaldi
  • 2,872
  • 2
  • 32
  • 37