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

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.

Related

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

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

Why do my pictures not render when using react?

I used default create-react-app to create a react app. However, when i try to add cards that contain pictures my image does not render. I get a white screen....
My image is located in a folder in src called Images. The rest works until I add in the Card prop and then the screen goes fully white. So I suppose that means it is not working or rendering properly.
import React from 'react';
export default function Card(props) {
return (
<div className="card">
<img src={require("./Images/monstera.jpeg")} alt="monstera"></img>
<div className="card-stats">
<p>{props.name}</p>
<p>{props.price}</p>
</div>
</div>
)
}
import logo from './logo.svg';
import './App.css';
import React from 'react';
import Header from './Components/Header';
import Inventory from './Components/Inventory';
import Cart from './Components/Cart';
import data from './data';
import Card from './Components/Card';
function App() {
return (
<div className="App">
<Header></Header>
<div className="row">
<Inventory>
<div className="cards-list">
<Card>
</Card>
</div>
</Inventory>
<Cart></Cart>
</div>
</div>
);
}
export default App;
Is there something I am doing wrong? Is there a special way to render a react app with an image?
look for any error through console and try cleaning your code a little
turn this
function App() {
return (
<div className="App">
<Header></Header>
<div className="row">
<Inventory>
<div className="cards-list">
<Card>
</Card>
</div>
</Inventory>
<Cart></Cart>
</div>
</div>
);
}
export default App;
into this
function App() {
return (
<div className="App">
<Header />
<div className="row">
<Inventory />
<div className="cards-list">
<Card />
</div>
<Cart />
</div>
</div>
);
}
export default App;
if not required don't use so many div

how can i display active route name in text reactjs

i tried like ${route} but to be honest i have no idea.
i want to put some helpful links bottom of website and it must show active links name to belong links
import React from 'react'
import './Links.css';
function Links() {
return (
<div>
<div className="links_person">
<div className="links_right_2">
<div className="links_right_cild_2">
<span className="links_span"> You can take look and learn more
about ${route}
</span>
</div>
</div>
</div>
</div>
)
}
export default Links
you can check current route by using useLocation from react-router-dom
something like this
import { useLocation } from 'react-router-dom';
import React from 'react';
import './Links.css';
function Links() {
const location = useLocation();
return (
<div>
<div className="links_person">
<div className="links_right_2">
<div className="links_right_cild_2">
<span className="links_span">
You can take look and learn more about : {location.pathname}
</span>
</div>
</div>
</div>
</div>
);
}

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 ?

Using fullpagejs in React, how to trigger function on active slide without re-rendering entire page

In my React app I am using fullpage.js to render two slides containing two different components. I want to run a function inside one of these only when it's the active slide. I tried below code, but once the state changes the entire ReactFullpage is re-rendered causing the first slide to be active again so I'm basically stuck in a loop.
My question is, how can I trigger a function inside the <Player /> component to run only if it's the active slide?
import React from "react";
import ReactFullpage from "#fullpage/react-fullpage";
import AlbumInfo from './AlbumInfo';
import Player from './Player';
class Album extends React.Component {
constructor(props){
super(props);
this.state={
playing: false
}
}
_initPlayer = (currentIndex, nextIndex) => {
if(nextIndex.index === 1) {
this.setState({playing:true})
}
}
render() {
return (
<ReactFullpage
licenseKey='xxxxxxxx-xxxxxxxx-xxxxxxxx-xxxxxxxx'
sectionsColor={["#000000"]}
afterLoad={this._initPlayer}
render={({ state, fullpageApi }) => {
return (
<div id="fullpage-wrapper">
<div className="section">
<AlbumInfo />
</div>
<div className="section">
<Player playing={this.state.playing} />
</div>
</div>
);
}}
/>
);
}
}
export default Album;
From docs:
just add the class 'active' to the section and slide you want to load first.
adding conditionally (f.e. using getActiveSection()) 'active' class name should resolve rerendering problem.
The same method/value can be used for setting playing prop.
Probably (I don't know/didn't used fullpage.js) you can also use callbacks (without state management and unnecessary render), f.e. afterSlideLoad
Update
The issue has been fixed on https://github.com/alvarotrigo/react-fullpage/issues/118.
Version 0.1.15 will have it fixed
You should be using fullPage.js callbacks afterLoad or onLeave as can be seen in the codesandbox provided on the react-fullpage docs:
https://codesandbox.io/s/m34yq5q0qx
/* eslint-disable import/no-extraneous-dependencies */
import React from "react";
import ReactDOM from "react-dom";
import "fullpage.js/vendors/scrolloverflow"; // Optional. When using scrollOverflow:true
import ReactFullpage from "#fullpage/react-fullpage";
import "./styles.css";
class FullpageWrapper extends React.Component {
onLeave(origin, destination, direction) {
console.log("Leaving section " + origin.index);
}
afterLoad(origin, destination, direction) {
console.log("After load: " + destination.index);
}
render() {
return (
<ReactFullpage
anchors={["firstPage", "secondPage", "thirdPage"]}
sectionsColor={["#282c34", "#ff5f45", "#0798ec"]}
scrollOverflow={true}
onLeave={this.onLeave.bind(this)}
afterLoad={this.afterLoad.bind(this)}
render={({ state, fullpageApi }) => {
return (
<div id="fullpage-wrapper">
<div className="section section1">
<h3>Section 1</h3>
<button onClick={() => fullpageApi.moveSectionDown()}>
Move down
</button>
</div>
<div className="section">
<div className="slide">
<h3>Slide 2.1</h3>
</div>
<div className="slide">
<h3>Slide 2.2</h3>
</div>
<div className="slide">
<h3>Slide 2.3</h3>
</div>
</div>
<div className="section">
<h3>Section 3</h3>
</div>
</div>
);
}}
/>
);
}
}
ReactDOM.render(<FullpageWrapper />, document.getElementById("react-root"));
export default FullpageWrapper;

Resources