tensm
tensm

Reputation: 11

Adding Variable to URL In React

I need to pass city name in URL. I have declared Variable city and I am passing it in URL but it is not reading variable I have tried many methods but they are not working.

   const Weather=({city})=>{
  const [weather,setWeather]=useState('')
    useEffect(() => {
  
    axios
      .get(`http://api.weatherstack.com/current?access_key=58hgf1d8d36bf336f347d6cc9fbc7&query=${city}`)
      .then(response => {
        setWeather(response.data) 
      })
  }, []) 
// ...

Upvotes: 0

Views: 916

Answers (2)

Roger Jacob
Roger Jacob

Reputation: 360

It should be ` instead of ' as follows:

axios.get(`http://api.weatherstack.com/current?access_key=Your_access_Key&query=${city}`)
    .then(response => {
      setWeather(response.data) 
    })

Hope this resolves the issue while passing dynamic city to the URL. Also make sure that you are passing the right access_key too.

Upvotes: 1

Jamie Counsell
Jamie Counsell

Reputation: 8113

You're using incorrect template literal syntax. You need:

.get(`http://api.weatherstack.com/current?access_key=Your_access_Key&query=${city}`)

But it also looks like you're missing an access key in this request.

Upvotes: 2

Related Questions