Search code examples
javascriptreactjsapireact-hooksget

Error 400 when parameter in API request is set as a State in React


This is a get request to get weather details of a location. Here's what my code looks like:

const [weather, setWeather] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
const [location, newLocation] = useState("Mumbai");

const locationHandler = (place) => {
newLocation(place);
};

const fetchweatherHandler = useCallback(async () => {
setIsLoading(true);
setError(null);
try {
  console.log(location);
  const response = await fetch(
    `http://api.weatherapi.com/v1/current.json?key=<api_key>&q=${{
      location,
    }}&aqi=yes`
  );

  if (!response.ok) {
    throw new Error("Something went wrong!");
  }

  const data = await response.json();
  console.log(data);
  setWeather(data);
} catch (error) {
  setError(error.message);
}
setIsLoading(false);
weather && console.log(weather);
}, []);

 useEffect(() => {
fetchweatherHandler();
}, [fetchweatherHandler]);

In the get request q="Mumbai" yields 200 status code but when replaced with ${{location}} so that weather can be displayed in terms of user input, yields a 400 status code.

I can't seem to understand why is this so.


Solution

  • Why are you doubling the curly braces in the template string? That creates an object, which isn't the output you want:

    const test = "Mumbai";
    console.log(`http://api.weatherapi.com/v1/current.json?key=<api_key>&q=${{test}}&aqi=yes`);

    (You can, and should, observe this in your debugging by simply outputting the resulting value, or by observing the URL of the request in your browser's debugging tools.)

    Just use one set of curly braces to evalutate the string value:

    const test = "Mumbai";
    console.log(`http://api.weatherapi.com/v1/current.json?key=<api_key>&q=${test}&aqi=yes`);