I fetched some data from a third party API and then console.logged it. However, it is displaying as null in the console (It is actually an empty string). Something I noticed was that it was requested multiple times. How can I store the string into a variable? Is it a problem with the way I get the data or is it how I am storing it?
import { ThemeProvider, createTheme } from "@mui/material/styles";
import React from "react";
import { CssBaseline } from "@mui/material";
import { useState } from "react";
import { Alert } from "@mui/material";
import { useEffect } from "react";
// Dark theme
function App() {
const [ready, setReady] = useState(false);
const [requestUrl, setRequestUrl] = useState("");
const [zuhrtime, setZuhrtime] = useState("");
useEffect(() => {
fetchData();
}, [ready]);
const darkTheme = createTheme({
palette: {
mode: "dark",
},
});
// api variables
const api1 = "https://api.aladhan.com/v1/timings/";
const api2 = "?latitude=";
const api3 = "&longitude=";
// Get location
const [showAlert, setShowAlert] = useState(false);
const getMyLocation = () => {
const success = (position) => {
//console.log(position);
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
const timestamp = position.timestamp;
setRequestUrl(api1 + timestamp + api2 + latitude + api3 + longitude);
setReady(true);
//console.log(requestUrl);
//console.log(timestamp);
setShowAlert(true);
setReady(true);
};
const error = () => {
console.log("error");
setShowAlert(false);
};
navigator.geolocation.getCurrentPosition(success, error);
};
// Get request from api
const fetchData = async () => {
const response = await fetch(requestUrl);
let adata = await response.json();
console.log(adata);
setZuhrtime(adata.status); // what I want to display
setZuhrtime(adata.data.timings.Dhuhr); // also what I want to display
console.log(zuhrtime);
};
return (
<ThemeProvider theme={darkTheme}>
<CssBaseline />
<h2>
{showAlert ? (
<Alert variant="filled" severity="success">
Location Accessed
</Alert>
) : (
<Alert variant="filled" severity="error">
Unable to get location. Enable location to use this
</Alert>
)}
</h2>
{getMyLocation()}
</ThemeProvider>
);
}
export default App;