i CAnt display items from appsync api - javascript

import logo from './logo.svg';
i need to list items from my appsync api in my react app ...i cant display as it says the error its undefined ...which i mentioned bellow the code..i know my code is wrong can somebody guide me
import React, { useState } from "react";
import { API, graphqlOperation } from 'aws-amplify';
import { listTestModels } from "./graphql/queries/list";
import './App.css';
function App() {
const [list, setBook] = useState(null);
const getBook = async () => {
// make a call to appsync api
const list = await API.graphql(graphqlOperation(listTestModels));
setBook(list.data.listTestModels.items);
}
const viewBook = () => {
if (list) {
**it shows error after this **
return (<article>
<h3>{list.data.listTestModels.items}</h3>
<p>{list.Location}</p>
<p>{list.Email}</p>
</article>)
}
}
return (
<div>
<section className="book-section">
<button onClick={() => getBook()}>Get book details</button>
<hr />
{viewBook()}
</section>
</div>
);
}
export default App;```
**it shows error App.js:24 Uncaught TypeError: Cannot read properties of undefined (reading 'listTestModels')**

list.data is undefined. Change the condition to list && list.data
const viewBook = () => {
if (list && list.data) {...}
}
But if the data key doesn't exist in the list object . It will never render the viewBook.

Related

React undefined property when send to child component

I want to send the login user object to the profile page to edit and upload an image but It ends with the error "ProfileImage.jsx:25 Uncaught TypeError: Cannot read properties of undefined (reading 'photoUrl')"
Here is my Parent Code :
import React from 'react';
import { useState } from 'react';
import {getCurrentUser, logout} from '../../services/authService'
import {useNavigate} from "react-router-dom";
import UpdateForm from '../../components/UpdateForm';
import ProfileImage from '../../components/ProfileImage';
import './Profile.css'
import { useEffect } from 'react';
const ProfilePage = () => {
const navigate = useNavigate();
const [user,setUser] = useState();
useEffect(()=>{
const getUser = async () => {
const {data} = await getCurrentUser();
setUser(data);
}
getUser()
},[])
const handelSignOut =()=>{
logout();
setUser('');
navigate('/sign')
}
return (
<div className='prof-con'>
<div className='prof-flex-wraper'>
<div className='prof-second-row'>
<div className='prof-text'>
<ProfileImage user={user}/>
</div>
<div className='prof-form'>
<UpdateForm user={user}/>
</div>
</div>
</div>
</div>
);
}
export default ProfilePage;
and here is the profile Child component
import React from 'react';
import { useState } from 'react';
import {updatePhoto} from '../services/authService'
import DefaultUserPic from "../images/team-male.jpg";
function ProfileImage({user}) {
const [previewSrc,setPreviewSrc] = useState(null)
const [photoSrc,setPhotoSrc] = useState(null)
const handelPreview = (e)=>{
setPreviewSrc(URL.createObjectURL(e.target.files[0]))
setPhotoSrc(e.target.files[0]);
}
const handelUpload = ()=>{
const formData = new FormData();
console.log(photoSrc)
formData.append("file", photoSrc);
updatePhoto(formData);
}
//console.log(user.photoUrl)
console.log(user)
// if(previewSrc){
// var imagestr=previewSrc;
// console.log(imagestr)
// // imagestr = imagestr.replace("public/", "");
// // var profilePic="http://localhost:3001/"+imagestr;
// }else{
// var profilePic='DefaultUserPic';
// }
return (
<div className='profWraper'>
<input type="file" name="fileToUpload" id="fileToUpload" onChange={handelPreview}/>
<img className='profPhoto' src={previewSrc} alt="No-Image" />
{photoSrc && <button className='uploadBtn' onClick={handelUpload}>Upload</button>}
</div>
);
}
export default ProfileImage;
if I log the user itself I get it in the console but if I try to get any property get an error undefined.
Changing
<ProfileImage user={user}/>
to
{user && <ProfileImage user={user}/>}
might help
You are asynchronously assigning user within the useEffect of ProfileImage. That means user will be undefined until that asynchronously logic resolves. You either have to check to see if user is defined before accessing its properties, or you need to assign user some kind of default properties in your useState.
The error message suggests that user is undefined. Considering that the parent performs an async operation to get the user, I'd say the problem is that the child tries to access the user before the async operation is resolved.
Solution, add a guard against undefined user in the child:
if (user === undefined) return

Passing object as prop returns undefined in destination component ReactJS

I'm trying to pass a JSON object (id) returned from an API call to another component via props and use that object(id) to fetch more data from a different endpoint. The problem is, when i pass the prop using object literal to the api, it gives an error undefined but when i console log the object(id) it works fine. What could be the issue? Just started learning React.
component passing object as prop
import axios from "axios";
import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import Cast from "./Cast";
const DetailsView = () => {
const { id } = useParams();
const [details, setDetails] = useState([]);
useEffect(() => {
axios
.get(
`https://api.themoviedb.org/3/movie/${id}?api_key=<<api_key>>&language=en-US`
)
.then((response) => {
setDetails(response.data);
});
}, []);
return (
<div className="w-full h-[650px] text-white">
<<bunch of code>>
<Cast id={details?.id}/>
</div>
);
};
export default DetailsView;
component receiving prop
import React, { useState, useEffect } from "react";
import axios from "axios";
const Cast = (props) => {
const [cast, setCast] = useState([]);
const sid = props.id;
useEffect(() => {
axios
.get(
`https://api.themoviedb.org/3/movie/${sid}/credits?api_key=<<api_key>>&language=en-US`
)
.then((response) => {
setCast(response.data.cast);
console.log(response.data.cast);
});
}, []);
console.log(sid);
return (
<div className="absolute">
{cast && cast.map((item, index) => <p className="">{item.name}</p>)}
<p>{sid}</p>
</div>
);
};
export default Cast;
It doesn't work initially but when I edit the code, since the change is happening live, it fetches the data but when I refresh the page, Axios reports an error 404
xhr.js:220 GET https://api.themoviedb.org/3/movie/**undefined**/credits?api_key=56fbaac7fd77013cc072d285a17ec005&language=en-US 404
Your id property does not exist until the API call is completed, and there is a rerender after setDetails.
You can check if id exists and based on that render your Card component. Also, looks like details is an object not an array, so I changed the useState statement to reflect that.
import axios from "axios";
import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import Cast from "./Cast";
const DetailsView = () => {
const { id } = useParams();
const [details, setDetails] = useState({});
useEffect(() => {
axios
.get(
`https://api.themoviedb.org/3/movie/${id}?api_key=<<api_key>>&language=en-US`
)
.then((response) => {
setDetails(response.data);
});
}, []);
return (
<div className="w-full h-[650px] text-white">
<<bunch of code>>
{details?.id && <Cast id={details?.id}/>}
</div>
);
};
export default DetailsView;

TypeError: Cannot read properties of undefined (reading 'map') in react redux

I am trying to create a simple web application which lists products from fakestore api using REACT REDUX. But react is throwing the error "TypeError: Cannot read properties of undefined (reading 'map')".
productListing.jsx
import React, { useEffect } from 'react';
import axios from 'axios';
import { useDispatch, useSelector } from 'react-redux';
import { setProducts } from '../redux/actions/productActions';
import ProductComponent from './ProductComponent';
const ProductListing = () => {
// const products = useSelector((state) => state.allProducts.products);
const dispatch = useDispatch()
const fetchProducts = async () => {
const response = await axios
.get("https://fakestoreapi.com/products")
.catch((err) => {
console.log("Err: ", err);
});
dispatch(setProducts(response.data));
console.log(response.data)
};
useEffect(() => {
fetchProducts()
},[])
// console.log("Products :" , products)
return (
<div className="ui grid container">
<ProductComponent />
</div>
);
};
export default ProductListing;
The above component is responsible for api call from fakestoreapi and updating the redux store.
In the following component named "productComponent.jsx" i tried to list the products from the redux store using map method which is as follows :
import React from 'react'
import { useSelector } from 'react-redux'
const ProductComponent = () => {
const pdts = useSelector((state) => state.allProducts.products);
// console.log(typeof(pdts))
console.log("Products",pdts)
const renderList = pdts.map((pdt) => {
// const { id, title, image, price, category } = pdt;
return(
<div className="four column wide" key={pdt.id}>
<div className="ui link cards">
<div className="card">
<div className="image">
<img src={pdt.image} alt={pdt.title} />
</div>
<div className="content">
<div className="header">{pdt.title}</div>
<div className="meta price">$ {pdt.price}</div>
<div className="meta">{pdt.category}</div>
</div>
</div>
</div>
</div>
)
})
return(
<>{renderList}</>
// <>gbdf</>
)
}
export default ProductComponent
But React is throwing the folowing error :
Error Image
when i consoled the products object it shows undefined. But after I commented renderlist and again consoled the products object it consoled two time with the first one being undefined and second one printing the correct object with values. At this point of time I uncommented the render list, now the react is listing the products but when i again reload the page it consoles undefined value for two times.
Pdts is undefined in the first render. Hence cant be mapped.
Try this
pdts?.map()
It's known as Optional Chaining.

How Do you display data from an api in React?

Weather.JS File
import { useEffect, useState } from "react"
import axios from 'axios'
import WeatherDisplay from './WeatherDisplay'
const Weather = ({capital, params}) => {
const [weather,setWeather] = useState([])
useEffect(async () => {
const result = await axios.get('http://api.weatherstack.com/current', {params})
console.log(result.data)
setWeather(result.data)
},
[params])
return(
<div>
<h2>Weather in {capital}</h2>
<WeatherDisplay current={weather.current}/>
</div>
)
}
export default Weather
WeatherDisplay.js File
const WeatherDisplay = ({weather}) => {
console.log(weather.current.temperature)
return (
<h1>{weather.current.temperature}</h1>
)
}
export default WeatherDisplay
Having issues display the data when i use {weather.current.temperature}, it keeps giving me an error pointed at temperuture saying it isnt defined but its apart of the data
You are passing weather.current as props. While the child component is expecting weather as prop. So, what you end up doing is weather.current.current.temperature which is undefined because it doesn't exist. Just pass weather to the child prop.
Make this change when calling your child component.
<WeatherDisplay weather={weather}/>

React Fetch not Fetching

In my App.js function, when it first loads, I want to fetch a website. This website contains .json data. The console gives the following error when I try to fetch the website:
App.js:9 GET https://geolocation-db.com/json/344ec440-6bfc-11eb-a0c0-b5dee9e67313 net::ERR_BLOCKED_BY_CLIENT
localhost:/1 Uncaught (in promise) TypeError: Failed to fetch
App.JS:9 GET https://geolocation-db.com/json/344ec440-6bfc-11eb-a0c0-b5dee9e67313 net::ERR_BLOCKED_BY_CLIENT
localhost:/1 Uncaught (in promise) TypeError: Failed to fetch
When I visit the website through the web browser, I'm able to see the JSON.
My App.js Code:
import logo from './logo.svg';
import './App.css';
import Weather from './Weather'
import React, { Component, useState } from "react";
function App() {
const [details, setDetails] = useState("0");
fetch("https://geolocation-db.com/json/344ec440-6bfc-11eb-a0c0-b5dee9e67313")
.then(response => response.json())
.then((data) => {
setDetails(data)
console.log("hi")
} );
return (
<div className="App">
<div className="weatherWrap">
<Weather longg="0" lat="0" name="China"/>
</div>
</div>
);
}
export default App;
I'm assuming I'm fetching the website incorrectly. I also think that the way I did it, it will keep fetching every time. While I only want it to fetch once. Please let me know how to fix it. Thanks!
Try below piece of code:
const url = 'https://geolocation-db.com/json/344ec440-6bfc-11eb-a0c0-b5dee9e67313';
function App() {
const [details, setDetails] = useState([]);
const getDetails = async()=>{
const response = await fetch(url);
const details = await response .json();
setDetails(details );
}
useEffect(() => {
getDetails();
},[]);
}
Here is the code that will work for you. Link
import "./styles.css";
import { useEffect, useState } from "react";
export default function App() {
const [details, setDetails] = useState("0");
useEffect(() => {
fetch(
"https://geolocation-db.com/json/344ec440-6bfc-11eb-a0c0-b5dee9e67313"
)
.then((response) => response.json())
.then((data) => {
console.log(data);
});
}, []);
return (
<div className="App">
<div className="weatherWrap">hello world</div>
</div>
);
}

Categories

Resources