Run Function after useEffect to Manipulate Data?
mitchelln11
Posted on June 12, 2020
I'm using the OpenWeather REST API which comes in JSON format. I know I have to make my fetch,(Axios in my case) call inside the useEffect because the component needs to render first, then calls the REST endpoint.
I can log out the information, only the temperature comes in Kelvin. In this case, I need to create another function that does the conversion. The only thing I am stuck on is how to transfer the API object info to my temperature conversion function. Any thoughts on how to do this? I assume props are involved.
My Code:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import {KelvinConvert} from './MathConversions';
const LocalWeather = () => {
const [openWeather, setWeather] = useState({});
useEffect(() => {
axiosGet();
}, []); // Run once on load
const axiosGet = () => {
axios.get(`https://api.openweathermap.org/data/2.5/weather?q=London,uk&APPID=${process.env.REACT_APP_WEATHER_KEY}`)
.then(data => setWeather(data.data));
}
return (
<ul id="weather-container">
<KelvinConvert /> // Trying to add converted temperature here
<li>{openWeather.main && openWeather.main.temp}°F</li>
<li>{openWeather.weather && openWeather.weather[0].main}</li>
<li>{openWeather.name}</li>
</ul>
);
}
export default LocalWeather;
Then there's my method to do the conversion.
import React, {useState, useEffect} from 'react';
export const KelvinConvert = props => {
const [temperature, setTemperature] = useState({props});
useEffect(() => {
convertKelvinToFahrenheit();
}, []);
const convertKelvinToFahrenheit = props => {
setTemperature(((props - 273.15) * 9/5) + 32);
}
return {temperature};
}
Not actually properly passing data to the convertKelvinToFahrenheit method.
Getting the following errors:
./src/components/MathConversions.js
Line 1:8: 'React' is defined but never used
no-unused-vars
Line 4:10: 'temperature' is assigned a value but never used
no-unused-vars
Compiled with warnings.
Not sure where to go from this point.
Posted on June 12, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.