Weather Api with React

Viewed 114

I am quite new to React so I have a simple question I think. I am trying to take the weather description from the API and according to that, I am trying to show different images. I wrote a function getForecast and response.data.weather[0].description turns the right value. So according to that, I am assigning 'image' to different SVG's but in doesnt turn right.

import React, { useState } from 'react';
import axios from 'axios';
import './Products.css';
import ProductItem from './ProductItem';
import Weather from './Weather';
import { Container, Row, Col } from 'react-bootstrap';

function Products() {

  const [imageTemp, setImage] = useState('images/umbrella.svg');
  const getForecast = () => {

    axios({
      method: "GET",
      url: 'http://api.openweathermap.org/data/2.5/weather?q=Kaunas&appid=7e6e14c967d752abbafb23a1f251b21c'
    })
      .then((response) => {
        console.log(response.data.weather[0].description);
        if (response.data.weather[0].description === "overcast clouds") {
          setImage('images/umbrella.svg');
        }
        else if (response.data.weather[0].description === "clear") {
          setImage('images/sunglasses.svg');
        }
        else {
          setImage('images/snowflake.svg');
        }
      })
      .catch((error) => {
        console.log(error);
      });
  };
  
  return (
    <div className='products'>
      <Container className="products-container">
        <h2 className="products__title">Products</h2>
        <h6 className="products__subtitle">Offers Today</h6>
        <Row>
          <Col xs="12" md="6" lg="6">
            <Weather
              src={imageTemp}
              path='/'
            />
          </Col>
          <Col xs="12" md="6" lg="6">
            <ProductItem
              src='images/img-2.jpg'
              text='The Best Coffee'
              path='/'
            />
            <ProductItem
              src='images/img-3.jpg'
              text='Top 100 Books'
              path='/'
            />
          </Col>
        </Row>
      </Container>
    </div>
  );
}

export default Products;

And here is my Weather component:

import React from 'react';

function Weather(props) {
    return (
        <div className='banner__item'>
            <figure className='banner__item__pic-wrap'>
                <img
                    className='banner__item__img'
                    src={props.src}
                />
            </figure>
        </div>
    );
}

export default Weather;
2 Answers

You must use useEffect to call this method(getForecast)... Add this part to your code

 useEffect(() => {
   getForecast();
  }, [imageTemp]);

I think there's not a call for getForecast anywhere.

If you wanna know how to call the function at the time you want, i'll recommend you to look into useEffect hook in detail.

Related