0

From this API I want to take from list[0].main.temp, list[0].dt_txt to list[39].main.temp, list[39].dt_txt

I want to get temperature and date and want to display on X axis temperature on Y axis dates.

import logo from './Images/logo.png';
import './App.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import { Nav, Navbar, Button, Form, FormControl } from 'react-bootstrap';
import React, { Component } from "react";
import { LineChart, Line, CartesianGrid, XAxis, YAxis, Tooltip } from 'recharts';

const data = [
  { name: 'Page A', uv: 400, pv: 2400, amt: 2400 },
  { name: 'Page B', uv: 600, pv: 2600, amt: 1800 },
  { name: 'Page C', uv: 800, pv: 2800, amt: 1200 }
];
class App extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentDidMount() {
    if (navigator.geolocation) {
      navigator.geolocation.watchPosition(async (position) => {

        var lat = position.coords.latitude;
        var lon = position.coords.longitude;

        const url = `http://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&units=metric&appid=ca148f5dc67f12aafaa56d1878bb6db2`;
        const response = await fetch(url);
        let data = await response.json();

        this.setState(data);

        const urlForecast = `http://api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${lon}&units=metric&appid=ca148f5dc67f12aafaa56d1878bb6db2`;
        const responseForecast = await fetch(urlForecast);
        let dataForecast = await responseForecast.json();

        this.setState(dataForecast);
      });
    }

  }

render() {
    return (
      <div className="App">


        <LineChart width={600} height={300} data={data} >
          <Line type="monotone" dataKey="uv" stroke="#8884d8" />
          <CartesianGrid stroke="#ccc" strokeDasharray="5 5" />
          <XAxis dataKey="name" />
          <YAxis />
          <Tooltip />
        </LineChart>


      </div>
    );
  }
}

export default App;

For now I have array data under the imported libraries and want to put inside all objects from the API list[0].main.temp, list[0].dt_txt to list[39].main.temp, list[39].dt_txt and display this data in x and y axis on the chart. Is there a way to get some example how to put my dataForecast from the API in the chart ?

UPDATE

I create a data.js file with static data and use like this:

    import weatherData from "./data";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      chartData: []
    };
  }

  formatData = (data) =>
    data.map(({ dt_txt, main }) => ({
      // date -> Can be used as dataKey for XAxis
      //Further you can format the date as per your need
      date: dt_txt,
      // temp -> Can be used as dataKey for Line
      temp: main.temp
    }));

My componentDidMount() look like this:

 componentDidMount() {
if (navigator.geolocation) {
  navigator.geolocation.watchPosition(async (position) => {

    var lat = position.coords.latitude;
    var lon = position.coords.longitude;

    const url = `http://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&units=metric&appid=ca148f5dc67f12aafaa56d1878bb6db2`;
    const response = await fetch(url);
    let data = await response.json();

    this.setState(data);

    const urlForecast = `http://api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${lon}&units=metric&appid=ca148f5dc67f12aafaa56d1878bb6db2`;
    const responseForecast = await fetch(urlForecast);
    let dataForecast = await responseForecast.json();

    this.setState(dataForecast);

    const fetchData = async () => {
      // Commenting as getting error while fetching
      // But here you can have logic of fetching the data and
      //add listeners etc
       let res = await fetch(
        `http://api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${lon}&units=metric&appid=ca148f5dc67f12aafaa56d1878bb6db2`
       );
       res = await res.json();

      //Here i'm using dummy promise to simulate the API call
      const promise = new Promise((res) => {
        setTimeout(() => {
          res(weatherData);
        }, 500);
      });
       res = await promise;

      //After getting the data from the backend,
      //format it as per how the LineChart is expecting
      this.setState({
        chartData: this.formatData(res.list)
      });
    };
    fetchData();
  });
}

}

How to use data from fetchData function on the chart ?

1 Answer 1

1

As per what I understand, you just need to format the data in such a way that the Line & LineChart components are expecting them to be.

  formatData = (data) =>
    data.map(({ dt_txt, main }) => ({
      // date -> Can be used as dataKey for XAxis
      //Further you can format the date as per your need
      date: dt_txt,
      // temp -> Can be used as dataKey for Line
      temp: main.temp
    }));

You can call this method once after getting the data from backend and set the result in the state and provide it to the LineChart component.

Once after response is received you can call formatData and get the formatted data and set it like

this.setState({
  chartData: this.formatData(res.list)
});

Finally, you can pass the data to LineChart and Line as

<LineChart width={600} height={300} data={chartData}>
  <Line type="monotone" dataKey="temp" stroke="#8884d8" />
  <CartesianGrid stroke="#ccc" strokeDasharray="5 5" />
  <XAxis dataKey="date" />
  <YAxis />
  <Tooltip />
</LineChart>

I have created this sandbox for the same. Please check this out if it's addressing what you are looking for.

Sign up to request clarification or add additional context in comments.

4 Comments

I go to work now after 30 minutes I will check and will accept your answer. Thank you very much 🙏
Nithish thank you very much for your example, now I update the question with worked componentDidMount.. can you tell me how to use data from fetchData function on my chart ?
Hey @BlagovestPizhev, I have added that new Promise(....) code just to simulate the API response from backend. You can remove from your actual implementation. And you don't have to do anything other than just calling fetchData, which will eventually call API and get response and set the formatted data in component state i.e., chartData. And we are passing chartData as prop to LineChart
I just replace weatherData with dataForecast in res(weatherData); in promise and new data is here ... Thank you man and have a very good day :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.