Can someone tell me why my app crashes when I refresh the page? - reactjs

I added a weather component in my app that fetches weather from open weather map. It works fine until I refresh the page, then it breaks.
If I comment the weather component out when refreshing and then add it back in when loaded it renders and works.
I'm not sure what's causing this error.
Here's some images of the console after refreshing for reference.
It seems to be undefined when refreshed. What's causing this issue?
// Weather component is called as normal in Home page
<div className="main-section-one">
<Weather />
<ToDoWidget />
</div>
import React, { useEffect, useState } from 'react'
//CSS
import '../css/Weather.css'
function Weather() {
// API
const URL = 'https://api.openweathermap.org/data/2.5/weather?q=barcelona&appid=APIKEY';
// State
const [weatherDetails, setWeatherDetails] = useState({});
async function getWeather() {
let fetchUrl = await fetch('https://api.openweathermap.org/data/2.5/weather?q=barcelona&appid=APIKEY&units=metric');
let data = await fetchUrl.json()
setWeatherDetails(data)
}
//Use Effect
useEffect(() => {
getWeather();
}, [])
return (
<div className="weather-container">
<div className="weather-one">
<div className="city">
<h3>Barcelona</h3>
<h1 className='temp'>{weatherDetails.main.temp}°C</h1>
</div>
<div className="current-weather">
<h3 className='current'>Sunny</h3>
</div>
</div>
<div className="weather-two">
<div className="">
<p>{weatherDetails.main.feels_like}°C</p>
<p className='weather-details'>Feels Like</p>
</div>
<div className="">
<p>{weatherDetails.main.humidity}%</p>
<p className='weather-details'>Humidity</p>
</div>
<div className="">
<p>{weatherDetails.wind.speed} MPH</p>
<p className='weather-details'>Wind Speed</p>
</div>
</div>
</div>
)
}
export default Weather

The main and wind properties may be undefined. Secure it.
<h1 className='temp'>{weatherDetails.main?.temp}°C</h1>
^^^ optional chaining
<p>{weatherDetails.wind?.speed} MPH</p>
Reference: Optional chaining

Related

I am unable to show data in my NextJS app using Sanity

Though the data is showing in the console but I am missing something. I am new to NextJS and Sanity.io. So Kindly help. Nextjs code is not showing data in the frontend.
This is the NextJs code:
import React from "react";
// import Layout from '../components/Layout';
import client from '../utils/client';
export const TermsAndPolicy = (props) => {
return (
<>
<div className="ease-in">
<div>
<h1 className="text-3xl font-medium text-center my-4">Terms and Conditions</h1>
<h4 className="text-xl mx-8 py-8 ">
<span>Last Updated:{props.terms.dateUpdated}</span>
</h4>
</div>
<div>
<div>
<h2>{props.title}</h2>
</div>
<p className="md:text-justify text-center mx-8 py-8">
{props.body}
</p>
</div>
</div>
</>
);
};
export default TermsAndPolicy;
export const getServerSideProps = async () => {
const query = `*[_type == "terms"]{
title,
subHeading,
dateUpdated,
url,
body
}`;
const terms = await client.fetch(query)
console.log(terms);
return {
props: {
terms
}
};
}
I have added the NextJs code above which shows that I have called the client and connected the app. But somehow I am unable to show the data from the backend into the frontend. Data in the console is showing as you can see below! So therefore it is connected properly. The data below is the data showing in console:
But data is not showing in the website. It is showing blank instead.

How can I link to another website in React?

I have these div cards with some information, and I would like to insert a link inside them, that redirects to another site. It didn't work with <a></a>. can anybody help me?
Thanks!
import React from "react";
function Card(props) {
return (
<div className="card">
<img className="img-logo" src={props.img} alt="image_logo" />
<h3 className="name"> {props.name}</h3>
<p className="paragraph"> {props.description}</p>
<a href={props.link}>Page</a>
</div>
);
}
export default Card;
You can use the <Link> component from react router.
If you are opening the url in new tab, make sure to use noopener and noreferrer so that the browser does not attach the current website's window variable to the newly opened url in the new tab, which can be a security loophole.
import { Link } from 'react-router-dom';
export const openInNewTab = (url) => {
const newWindow = window.open(url, '_blank', 'noopener,noreferrer');
if (newWindow) newWindow.opener = null;
};
function Card(props) {
return (
<div className="card">
<img className="img-logo" src={props.img} alt="image_logo" />
<h3 className="name"> {props.name}</h3>
<p className="paragraph"> {props.description}</p>
<Link href="#" onClick = {() => openInNewTab(props.link)}>Page</Link>
</div>
);
}

getStaticProps not working from components folder

Recently I made a question about this problem: typeError: Cannot read property 'map' of undefined.
I want to use a component with getStaticProps and put it in my pages/index.js, but I can't with my current code. BUT, if I put this component as a page (pages/component.js) and open like a different page it just work as it should do.
The component Galery.js code:
import styles from '../styles/galery.module.css'
import Image from 'next/image'
import Link from 'next/link'
import photo from '../public/01.png'
export const getStaticProps = async () => {
const res = await fetch('https://my-json-server.typicode.com/Leterinho/PortfolioInteriorDesign/card');
const datas = await res.json();
return {
props: { datas }
}
}
const Galery = ({ datas }) => {
return (
<div className={styles.galeryPage}>
<h1 className={styles.title}>Projetos</h1>
<div className={styles.galery}>
<div className={styles.categoryWrapper}>
<h4 className={styles.subTitle}>Escritório</h4>
<div className={styles.lineWrapper}>
<a className={styles.leftArrow}>❮</a>
<div className={styles.line}>
{datas.map((data) => (
<div className={styles.imageBox}>
<Image src={photo} width={400} height={200} layout="responsive" lazy="true" placeholder="blur" />
<div className={styles.linkContent}>
<span className={styles.name} key={data.id}>{data.name}</span>
<Link href=""><a className={styles.link}>Veja Mais!</a></Link>
</div>
</div>
))}
</div>
<a className={styles.rightArrow}>❯</a>
</div>
</div>
</div>
</div>
);
}
export default Galery;
API link: https://my-json-server.typicode.com/Leterinho/PortfolioInteriorDesign/card
And this is the structure that I would like to have:
Desirable Structure
And this is the structure that works as a page:
Structure that works
What I should do to work as I planned?
Data fetching methods like getStaticProps can only be used from page components (components inside pages folder). I'd suggest you fetch the data at the page level in index.js, and pass it down to your Galery component.
juliomalves is correct! Thanks.

Trying to append an API value to a controlled input field with React Hooks

When the component loads, I am making an axios call to a Geolocation API. If the user agrees to let the app get their location, it gets their zipcode. I am then trying to append the zipcode to the zipcode input field, but I can't figure out how to do it. This is my landing page.
import React, { useState, useEffect, useRef } from 'react';
import './App.scss';
import axios from 'axios';
import { FontAwesomeIcon } from '#fortawesome/react-fontawesome';
import { faBars } from '#fortawesome/free-solid-svg-icons';
import LandingPage from './components/landingPage';
function App() {
const[zipcode, setZipcode] = useState();
useEffect(() => {
axios({
"method":"GET",
"url":"https://find-any-ip-address-or-domain-location-world-wide.p.rapidapi.com/iplocation",
"headers":{
"content-type":"application/octet-stream",
"x-rapidapi-host":"find-any-ip-address-or-domain-location-world-wide.p.rapidapi.com",
"x-rapidapi-key":x-rapidapi-key,
"useQueryString":true
},
"params":{
"apikey":apikey
}
})
.then((response)=>{
console.log(response.data.zipCode);
setZipcode(response.data.zipCode);
})
.catch((error)=>{
console.log(error)
});
},[]);
return (
<div className="App" path='/'>
<header className='container'>
<div className='row'>
<div className='col-1'>
<button>
<h1><FontAwesomeIcon icon={faBars} /></h1>
</button>
</div>
<div className='col'>
<h1>MDNight</h1>
</div>
</div>
</header>
<LandingPage zipcode={zipcode} setZipcode={setZipcode} />
<footer className='container'>
<h2>Copyright 2020</h2>
</footer>
</div>
);
}
export default App;
And here is the child component.
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function LandingPage(props) {
function handleInputChange(e) {
props.setZipcode(e.target.value);
};
return (
<main className='container'>
<div className='row'>
<div className='col'>
<h1>Welcome to <span>MDNight</span>!</h1>
<h2>The website that makes your date night more convenient.</h2>
<p>Let's assume that you and your "Significant Other" would like to go out for a date night, however, you have to continually switch back and forth between websites looking at showtimes and trying to find a place to eat beforehand. Well, that's where <span>MDNight</span> comes in! We take your location, movie you're interested in seeing, , and show you theaters that are showing your movie, and a list of restaurants nearby. Sound Convenient to you? Enter your info below to get started!</p>
</div>
</div>
<div className='row'>
<div className='col'>
<label htmlFor='zipcodeInput'>Please Enter Your zipcode to get started!</label>
</div>
</div>
<div className='row'>
<div className='col'>
<input name='zipcodeInput' type="text" value={props.zipcode} onChange={handleInputChange} />
</div>
</div>
<div className='row'>
<div className='col'>
<button className='btn btn-primary'>Get Started!</button>
</div>
</div>
</main>
);
}
export default LandingPage;
I've only ever used useState and useEffect, so I don't know if one of the other hooks solves this problem, but if someone could show me how that would be amazing.
I found this answer from someone on a React FB group. I added defaultValue={props.zipcode} to the input and it worked perfectly. I did not know about defaultValue until today.
You do not need zipcode as a dependency of the useEffect hook in the App component. I would suggest having an empty array as your dependency array because you want this hook to run on mount only.

No Set State or Async but still "Can't perform state update on unmounted component" error

I have nearly given up with this. I can't get my component to work no matter what I do. I have read all the error posts here and on Google but still nothing. I get the error
Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
Here is my full code...
import React, { Component } from 'react;
// page title bar
import PageTitleBar from 'Components/PageTitleBar/PageTitleBar';
import {
NewsFeedWidget
} from "Components/Widgets";
// widgets data
import {
newsData,
} from './data';
export default class EcommerceDashboard extends Component {
render() {
return (
<div className="ecom-dashboard-wrapper">
<div className="content_container">
<div className="row">
<div className="col-sm-6 col-md-4 w-xs-full">
<NewsFeedWidget data={newsData} />
</div>
</div>
</div>
</div>
)
}
}
and NewsFeed.js
import React, { Component, Fragment } from 'react';
const NewsFeedWidget = ({ data }) => (
<div className="cardheader_container">
<div className="notification_container">
{data && data.map((d, key) => (
<div className="a_notification" key={key}>
<div className="not_header">
<div className="not_content">
<h5>{d.title}</h5>
<p>{d.subtitle}</p>
</div>
</div>
</div>
))}
</div>
</div>
}
export default NewsFeedWidget;
Obviously I am new at React so please explain how and what issue I am having. It's gonna be something dumb I bet but this is how i'll learn.
ty
Could you upload the code for PageTitleBar too ?

Resources