How can I call array data in a useEffect - ReactJS - javascript

I am trying to fetch the weather data of a farm with latitude and longitude coordinates. I have successfully managed to get the farm data from the Api to a React Component. And now I want to fetch the weather data of the farm using its coordinates. I am using openweathermap
But the Problem is, I keep getting this error: GET http://api.openweathermap.org/data/2.5/weather?lat=undefined&lon=undefined&appid=[API]&units=metric 400 (Bad Request)
Someone please help
Here is the Farm Component
import React, { useState, useEffect } from "react";
import { Link, useNavigate, useParams } from "react-router-dom";
import Menubar from "../../components/menubar/Menubar";
import Skeleton from "react-loading-skeleton";
import toast, { Toaster } from 'react-hot-toast';
import axios from 'axios';
import { LazyLoadImage } from "react-lazy-load-image-component";
import Weather from "../../components/weather/Weather";
import FarmWeather from "../../components/weather/FarmWeather";
function FarmDetails() {
let navigate = useNavigate();
const [farm, setFarm] = useState('');
const { username } = useParams();
const { farmId } = useParams();
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
let isMounted = true;
axios.get(`/api/farm/${username}/${farmId}`).then(res => {
if (isMounted) {
if (res.data.status === 200) {
setFarm(res.data.farm);
setIsLoading(false);
console.warn(res.data.farm)
}
else if (res.data.status === 404) {
navigate('/');
toast.error(res.data.message, "error");
}
}
});
return () => {
isMounted = false
};
}, []);
return (
<div>
<Menubar />
<div className="appHeader bg-primary text-light">
<div className="left">
<a onClick={() => navigate(-1)} className="headerButton goBack">
<i className="fi fi-rr-angle-left"></i> </a>
</div>
<div className="pageTitle">{farm.farmname}</div>
<div className="right"></div>
</div>
<div id="appCapsule">
<div className="section mt-3 mb-3">
<div className="card">
<div className="card-header">
Discover
</div>
<div className="card-body">
<h5 className="card-title">Farm Supplies</h5>
<p className="card-text">Order for farm supplies suitable for your farm and grow healthy fruits</p>
Go to Shop
</div>
</div>
</div>
<FarmWeather farm={farm} />
<div className="section mt-3 mb-3">
<div className="row">
<div className="col-6">
<div className="card card-normal">
<div className="card-body">
<h5 className="card-title title-small mb-2">Location</h5>
<div className="card-icon mb-0">
<i className="fi fi-rr-marker"></i>
</div>
</div>
</div>
</div>
<div className="col-6">
<div className="card card-normal card-add">
<a href="farm-fruits.php?view=<?php echo $row['farmid']; ?>">
<div className="card-body">
<h5 className="card-title title-small mb-2">Fruits</h5>
<div className="card-icon mb-0">
<i className="fi fi-rr-apple-whole"></i>
</div>
</div>
</a>
</div>
</div>
<div className="col-6">
<div className="card card-normal">
<div className="card-body">
<h5 className="card-title title-small mb-2">Sales</h5>
<div className="card-icon mb-0">
<i className="fi fi-rr-bolt"></i>
</div>
</div>
</div>
</div>
<div className="col-6">
<div className="card card-normal">
<div className="card-body">
<h5 className="card-title title-small mb-2">Expenses</h5>
<div className="card-icon mb-0">
<i className="fi fi-rr-settings"></i>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
export default FarmDetails;
And the Weather Component
import React, { useState, useEffect } from "react";
const FarmWeather = ({ farm }) => {
const [weather, setWeather] = useState({});
useEffect(() => {
fetch(`//api.openweathermap.org/data/2.5/weather?lat=${farm.latitude}&lon=${farm.longitude}&appid=[API]&units=metric`)
.then((result) => result.json())
.then((weather) => {
setWeather(weather);
});
}, []);
console.warn("result", weather)
return (
<div className="section mt-3 mb-3">
<div className="card text-white bg-primary mb-2">
<div className="card-header">Weather in <span>{weather.name}</span>
<div className="weather-icon">
<img src={`http://openweathermap.org/img/w/${weather.weather && weather.weather[0].icon}.png`} alt="weather icon" />
</div>
</div>
<div className="card-body">
<h5 className="card-title">Temp <span>{weather.main && weather.main.temp} °C</span></h5>
<p className="card-text">Our Technologies have discovered that the Current Weather around your Farm in {farm.county && farm.county.countyname} is
Mostly
<span id="description" ></span>
</p>
</div>
</div>
</div>
);
}
export default FarmWeather;

You need to check that farm is defined before making the api call, you can put it as a dependency.
useEffect(() => {
if (farm) fetch(`//api.openweathermap.org/data/2.5/weather?lat=${farm.latitude}&lon=${farm.longitude}&appid=[API]&units=metric`)
.then((result) => result.json())
.then((weather) => {
setWeather(weather);
});
}, [farm]);

Related

am Unable to calculate the prices in the cart List-ReactJS

I am doing a cart page here, the cart page will display the items to the which user has been added and it will display its price also. On the same page, i want to display the Grand total amount of all the items present on the cart Page in Payment Summary(order summary)
Please help me am new to React.
Here is my ReactJS code of Cart page
import React, { useEffect, useState } from 'react';
import { useHistory } from 'react-router';
import '../cart.css';
function Cart() {
const tvalue = 0;
const [cart, setCart] = useState([]);
const [paymentsummery, setpaymentsummery] = useState(0);
const [total, setTotal] = useState('');
const [loading, setLoading] = useState(true);
const [cartSate, setcartState] = useState(true);
const [id, setID] = useState('');
const history = useHistory();
useEffect(() => {
const fetchUser = async () => {
try {
const responce = await fetch('/getcartItems', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
});
const resp = await responce.json();
console.log(resp);
setCart(resp);
setLoading(false);
setID(resp[0]._id);
setcartState(true);
if (!responce) {
alert('user not authorized');
history.push('/');
} else if (responce.status == 400) {
history.push('/');
} else if (responce.status == 401) {
alert('cart is empty');
}
} catch {
// alert('cart is empty')
setcartState(false);
}
};
fetchUser();
}, []);
if (cartSate == true) {
return (
<div className="cart_cont row container-fluid">
{loading ? (
<div className="loading_div">
<h1 className="loading">Loading...</h1>
</div>
) : (
cart.map((itms, index) => (
<div key={index} className="innerCart my-0 col-8">
<div className="cartDetails">
<div className="slno d-flex flex-column">
<label htmlFor="" className="text-danger m-auto">
Sl.No
</label>
<p className="m-auto">{index + 1}</p>
</div>
<div className="cartImage ">
<img
src={itms.productimage}
alt="cart_image"
height="100px"
/>
</div>
<div className="title d-flex flex-column">
<label htmlFor="" className="text-danger m-auto">
Item Name
</label>
<p className="m-auto">{itms.productname}</p>
</div>
<div className="qty d-flex flex-column">
<label htmlFor="" className="text-danger m-auto">
Quantity
</label>
<p className="m-auto">{itms.qty}</p>
</div>
<div className="tprice d-flex flex-column">
<label htmlFor="" className="text-danger m-auto">
Price
</label>
<p className="m-auto">{itms.totalprice}</p>
</div>
<div className="d-flex ">
<i className="fas fa-trash m-auto" />
</div>
</div>
<hr />
</div>
))
)}
{loading ? (
<div />
) : (
<div className="priceDetails col-4 ">
<div className="innerPriceDetails rounded">
<h1 className="paymentSummery h3 p-2">Payment Summery </h1>
<div className=" d-flex justify-content-between mx-2 my-2">
<span>Transaction code</span>
<span>Vd7jl0rq9ppe</span>
</div>
<div className="coupen d-flex m-3 justify-content-between">
<input
type="text"
className="form-control mr-2"
placeholder="COUPON CODE"
/>
<button className="btn btn-info px-5">Apply</button>
</div>
<hr />
<div className="order_summery m-3">
<div className="d-flex justify-content-between">
<h5>Order Summery</h5>
<h5>Rs. </h5>
</div>
<div className="d-flex justify-content-between">
<h5>Shipping charges</h5>
<h5>Rs. 10</h5>
</div>
<div className="d-flex justify-content-between">
<h5>Additional services</h5>
<h5>Rs. 00</h5>
</div>
<div className="d-flex justify-content-between">
<h5 className="font-weight-bold">Total amount</h5>
<h5 className="font-weight-bold">Rs. 5400</h5>
</div>
<hr />
<p className="d-flex bg-danger expires text-white p-2 rounded justify-content-between">
Sale Expires in: 21Hours, 31 Minutes
</p>
</div>
</div>
<button className="btn btn-warning w-100 my-3 font-weight-bold p-2">
CHECKOUT
</button>
</div>
)}
</div>
);
}
return (
<div>
<h1 className="display-3 mt-5">CART IS EMPTY!</h1>
</div>
);
}
export default Cart;
above, I have shared my whole code of the cart page, Usually, the cart data will be displayed from the database.
Please help me.
For that, you would use Array.reduce to calculate for grandTotal:
Before your return function:
const grandTotal = cart.reduce((a, c) => a + c.totalprice, 0);
Then you can place grandTotal where ever you want to display it.

Filter not working proper in react its working only for first time also how to filter true and false

Here is my code
https://stackblitz.com/edit/react-nsxxqp?file=src%2FApp.js
and my local code is here how to filter i don't know i am new for react and JavaScript please help me i don't know how to finish my task.
import React, { useEffect, useState } from "react";
const Product = (props) => {
const [allButtons, setAllButtons] = useState([]);
const [product, setProduct] = useState([]);
useEffect(() => {
fetch("https://api.spacexdata.com/v3/launches?limit=100")
.then(response => response.json())
.then(productsList => {
setProduct(productsList);
setAllButtons(productsList);
});
}, []);
const onBtnClick = (e) =>{
setProduct(product.filter(i=>i.launch_year == e));
};
return(
<div className="container-fluid">
<div className="row">
<div className="col-xl-12">
<h2>SpacesX Launch Programme</h2>
</div>
</div>
<div className="row">
<div className="col-xl-2 col-lg-2 col-md-2 col-sm-2 col-xs-12">
<div className="inner">
<p className="bold">Filter</p>
<div className="col12 launchYear">
<p className="marg0">Launch Year</p>
{allButtons.map(productYr => (
<button
className="btn btn-primary btnSpacex"
key={productYr.launch_year}
onClick={(e) => onBtnClick(productYr.launch_year)}
>
{productYr.launch_year}
</button>
))}
</div>
<div className="clearfix" />
<div className="col12 launchYear">
<p className="marg0">Successful Launch</p>
<button className="btn btn-default btnSpacex">True</button>
<button className="btn btn-default btnSpacex">False</button>
</div>
<div className="clearfix" />
<div className="col12 launchYear">
<p className="marg0">Successful Landing</p>
<button className="btn btn-default btnSpacex">True</button>
<button className="btn btn-default btnSpacex">False</button>
</div>
</div>
</div>
<div className="col-xl-10 col-lg-10 col-md-10 col-sm-10 col-xs-12 items1">
<div className="row">
{product.map(product => (
<div
key={product.flight_number}
className="col-xl-3 col-lg-3 col-md-3 col-sm-3 col-xs-12 marginBottom15"
>
<div className="inner">
<img
src={product.links.mission_patch}
className="full-width imgBg"
alt={product.mission_name}
/>
<div className="clearfix" />
<p className="productName bold margBot5">
{product.mission_name} #{product.flight_number}
</p>
<div className="clearfix" />
<p className="bold margBot5">
Mission Ids:
<ul className="marg0 blueClr">
<li>{product.mission_id}</li>
</ul>
</p>
<div className="clearfix" />
<p className="bold margBot5">
Launch Year:{" "}
<span className="normal blueClr">
{product.launch_year}
</span>
</p>
<div className="clearfix" />
<p className="bold margBot5">
Successful Launch:{" "}
<span className="normal blueClr">
{product.launch_success}
</span>
</p>
<div className="clearfix" />
<p className="bold margBot5">
Successful Landing:{" "}
<span className="normal blueClr">
{product.rocket.land_success}
</span>
</p>
</div>
</div>
))}
</div>
</div>
</div>
</div>
)
}
export default Product
Main issue here is your onButtonClick function. Change it to the following code (instead of product.filter, use allButtons.filter):
const onBtnClick = e => {
setProduct(allButtons.filter(i => i.launch_year == e));
};
The problem was that you had all of your products, then when you selected the first button, you set the product to just that button. On the next click, you're trying to filter on just the single product that you selected in the first click. To get around this, you want the filter to always be on the allButtons list (I'm assuming this was just a small oversight on your part, it looks like you knew exactly what you were trying to do but just accidentally put the wrong list in the function).
Another small change that I would make to your code is below: (introduce index parameter and use it as the key):
{allButtons.map((productYr, index) => (
<button
className="btn btn-primary btnSpacex"
key={index}
onClick={e => onBtnClick(productYr.launch_year)}
>
{productYr.launch_year}
</button>
))
}
This will eliminate all those console warnings that you're getting for having duplicate keys.
Check below code
import React, { useEffect, useState } from "react";
const Product = (props) => {
const [allButtons, setAllButtons] = useState([]);
const [launchSuccess, launchAllSuccess] = useState([]);
const [landSuccess, landAllSuccess] = useState([]);
const [product, setProduct] = useState([]);
useEffect(() => {
fetch("https://api.spacexdata.com/v3/launches?limit=100")
.then(response => response.json())
.then(productsList => {
setProduct(productsList);
setAllButtons(productsList);
launchAllSuccess(productsList);
landAllSuccess(productsList);
});
}, []);
const onBtnClick = e => {
setProduct(allButtons.filter(i => i.launch_year === e));
};
const onBtnLaunchAllSuccess = e =>{
setProduct(launchSuccess.filter(i => i.launch_success === e));
}
const onBtnLandSuccessful = e =>{
setProduct(landSuccess.filter(i => i.rocket.first_stage.cores[0].land_success === e));
}
return(
<div className="container-fluid">
<div className="row">
<div className="col-xl-12">
<h2>SpacesX Launch Programme</h2>
</div>
</div>
<div className="row">
<div className="col-xl-2 col-lg-2 col-md-2 col-sm-2 col-xs-12">
<div className="inner">
<p className="bold">Filter</p>
<div className="col12 launchYear">
<p className="marg0">Launch Year</p>
{allButtons.map((productYr, index) => (
<button
className="btn btn-primary btnSpacex"
key={index}
onClick={e => onBtnClick(productYr.launch_year)}
>
{productYr.launch_year}
</button>
))
}
</div>
<div className="clearfix" />
<div className="col12 launchYear">
<p className="marg0">Successful Launch</p>
<button
onClick={e => onBtnLaunchAllSuccess(true)}
className="btn btn-default btnSpacex">True</button>
<button
onClick={e => onBtnLaunchAllSuccess(false)}
className="btn btn-default btnSpacex">False</button>
</div>
<div className="clearfix" />
<div className="col12 launchYear">
<p className="marg0">Successful Landing</p>
<button
onClick={e => onBtnLandSuccessful(true)}
className="btn btn-default btnSpacex">True</button>
<button
onClick={e => onBtnLandSuccessful(false)}
className="btn btn-default btnSpacex">False</button>
</div>
</div>
</div>
<div className="col-xl-10 col-lg-10 col-md-10 col-sm-10 col-xs-12 items1">
<div className="row">
{product.map(product => (
<div
key={product.flight_number}
className="col-xl-3 col-lg-3 col-md-3 col-sm-3 col-xs-12 marginBottom15"
>
<div className="inner">
<img
src={product.links.mission_patch}
className="full-width imgBg"
alt={product.mission_name}
/>
<div className="clearfix" />
<p className="productName bold margBot5">
{product.mission_name} #{product.flight_number}
</p>
<div className="clearfix" />
<p className="bold margBot5">
Mission Ids:
<ul className="marg0 blueClr">
<li>{product.mission_id}</li>
</ul>
</p>
<div className="clearfix" />
<p className="bold margBot5">
Launch Year:
<span className="normal blueClr">
{product.launch_year}
</span>
</p>
<div className="clearfix" />
<p className="bold margBot5">
Successful Launch:
<span className="normal blueClr">
{product.launch_success}
</span>
</p>
<div className="clearfix" />
<p className="bold margBot5">
Successful Landing:
<span className="normal blueClr">
{product.rocket.first_stage.cores[0].land_success}
</span>
</p>
</div>
</div>
))}
</div>
</div>
</div>
</div>
)
}
export default Product

How can I call a function inside of a .map of arrays?

I am passing down a function through props that capitalizes a few items being mapped over. I am getting an error on the item portion of item.creator.I am just wondering why I am recieving the error and not able to just call the function inside of the map. Thanks for your help.
Error message is Line Parsing error: Unexpected token, expected ",".
PARENT COMPONENT
export default function MainContent() {
const techContent = useSelector(displayTechContent);
const designContent = useSelector(displayDesignContent);
const makeCapital = (words) => words.replace(/^\w/, (c) => c.toUpperCase());
return (
<div className="container">
<div className="topics-list">
<div className="topic-row mb-5">
<h2 className="topic-heading mb-4">Software Development</h2>
<ContentCard data={techContent} capitalize={makeCapital} />
</div>
CHILD COMPONENT
export default (props) => (
<div>
<div className="resource-list">
{props.data.map((item) => (
<a key={item.id} href={item.link} className="resource-card-link mr-3">
<div className="card resource-card mb-2">
<div className="card-header">
<h4 className="resource-title">{item.title}</h4>
<span className="resource-creator">by: ***{props.capitalize({item.creator})}***.</span> <--this function
</div>
<div className="card-body py-3">
<div className="resource-description mb-2">
{item.description}
</div>
<div className="resource-type mb-2">
<i className="fas fa-book"></i> {item.type}
</div>
The curly braces around of item.creator are redundant.
export default (props) => (
<div>
<div className="resource-list">
{props.data.map((item) => (
<a key={item.id} href={item.link} className="resource-card-link mr-3">
<div className="card resource-card mb-2">
<div className="card-header">
<h4 className="resource-title">{item.title}</h4>
<span className="resource-creator">by: ***{props.capitalize(item.creator)}***.</span> <--this function
</div>
<div className="card-body py-3">
<div className="resource-description mb-2">
{item.description}
</div>
<div className="resource-type mb-2">
<i className="fas fa-book"></i> {item.type}
</div>

How to import the component in another component which include image in react js

I am working on some assignment of reactjs. There are many components are included .
I want to import one component into another components which include different images with it . How can I do it.
Here is the(portfolio items) component which export and include image source
PortItems.js
import React from "react";
const PortItems = () => {
return(
<div>
{/* Portfolio Item 1*/}
<div className="col-md-6 col-lg-4 mb-5">
<div className="portfolio-item mx-auto" data-toggle="modal" data-target="#portfolioModal1">
<div className="portfolio-item-caption d-flex align-items-center justify-content-center h-100 w-100">
<div className="portfolio-item-caption-content text-center text-white"><i className="fas fa-plus fa-3x"></i>
</div>
</div>
<img className="img-fluid" src="" alt="this is cabin image" />
</div>
</div>
</div>
)
}
export default PortItems;
Here is the code for main component which import PortItems
import React ,{Component} from "react";
import "../App.css";
import PortItems from "./PortItems";
import Cabin from "./images/cabin.png";
import Cake from "./images/cake.png";
import Circus from "./images/circus.png";
import Game from "./images/game.png";
import Safe from "./images/safe.png";
import Submarine from "./images/submarine.png";
const Portfollio = () =>{
return(
<div>
{/* Portfolio Section*/}
<section className="page-section portfolio" id="portfolio">
<div className="container">
{/* Portfolio Section Heading*/}
<h2 className="page-section-heading text-center text-uppercase text-secondary mb-0">Portfolio</h2>
{/* Icon Divider*/}
<div className="divider-custom">
<div className="divider-custom-line"></div>
<div className="divider-custom-icon"><i className="fas fa-star"></i></div>
<div className="divider-custom-line"></div>
</div>
{/* Portfolio Grid Items*/}
<div className="row">
* <PortItems
src={Cabin}
/>
*
Try adding props to the PortItem component and use it in its <img />tag:
const PortItems = (props) => {
return(
<div>
{/* Portfolio Item 1*/}
<div className="col-md-6 col-lg-4 mb-5">
<div className="portfolio-item mx-auto" data-toggle="modal" data-target="#portfolioModal1">
<div className="portfolio-item-caption d-flex align-items-center justify-content-center h-100 w-100">
<div className="portfolio-item-caption-content text-center text-white"><i className="fas fa-plus fa-3x"></i>
</div>
</div>
<img className="img-fluid" src={ props.src } alt="this is cabin image" />
</div>
</div>
</div>
)
}

Click on Link to show details of item - ReactJs, Node.js

App is running on Node.js and React. In database (mongodb used) I have collection Rooms that contains details about particular room.
On LandingPage I display some of room details and to se more person has to click on View link.
LandingPage.js
const Room = props => (
<div className = "col-md-4" >
<div className="card mb-4 shadow-sm">
<img src={props.room.imageData} class="card-img-top" alt="..." width="100%" height="225" />
<div className="card-body">
<h5 class="card-title">{props.room.title}</h5>
<p className="card-text">{props.room.description}</p>
<div className="d-flex justify-content-between align-items-center">
<div className="btn-group">
<Link className="btn btn-sm btn-outline-secondary" to={"/view/"+props.room._id}>View</Link>
</div>
</div>
</div>
</div>
</div >
)
Link is sending me to view page
<Link className="btn btn-sm btn-outline-secondary" to={"/view/"+props.room._id}>View</Link>
But I am not sure how would I display now all details of room from database?
View.js
export default class RoomsAdmin extends React.Component {
constructor(props) {
super(props);
this.state = { rooms: [] };
}
componentDidMount() {
axios.get('http://localhost:3090/admin/')
.then(response => {
this.setState({
rooms: response.data
})
.catch(function (error) {
console.log(error);
})
})
}
roomList() {
return this.state.rooms.map(function (currentRoom, i) {
return <Room room={currentRoom} key={i} />
});
}
render() {
console.log(this.props);
return (
<div>
<div className="album py-5 bg-light">
<div className="container">
<div className="row">
<div className="col-md-4">
<div className="card mb-4 shadow-sm">
<img src={props.room.imageData} className="card-img-top" alt="..." width="100%" height="225" />
<div className="card-body">
<h5 class="card-title">{props.room.title}</h5>
<p className="card-text">{props.room.description}</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
)
}
}
I came up with this code for now but I am getting following error:
Uncaught ReferenceError: props is not defined
Yes because you are writing props not this.props in your image tag.
In RoomAdmin Component
<img src={props.room.imageData} className="..../>
Use this instead
<img src={this.props.room.imageData} className=".../>

Categories

Resources