The app work perfectly locally. The error appears after i deploy it using firebase hosting. The code below is the component where i fetch the data from the api resource
import React, { useEffect, useState } from 'react'
import{ useSelector, useDispatch} from "react-redux"
import { setProducts } from "../containers/redux/actions/productActions"
import ProductComponent from './ProductComponent';
import axios from 'axios';
function ProductList() {
const products = useSelector((state) => state);
const dispatch = useDispatch()
const [searchValue, setSearchValue] = useState('');
const fetchProducts = async ( searchValue) => {
const response = await axios
.get(`http://www.omdbapi.com/?s=${searchValue}&apikey=??????`)
.catch((err) => {
console.log("Err", err);
});
if(response.data.Search){
dispatch(setProducts(response.data.Search));
}
};
useEffect(() => {
fetchProducts(searchValue);
// eslint-disable-next-line react-hooks/exhaustive-deps
},[searchValue]);
console.log("Products: " , products)
return (
<div className='home'>
<div className='search-box'>
<input
value={searchValue} onChange={(e) => setSearchValue(e.target.value)}
type="text"
placeholder="Search.."
>
</input>
</div>
<div className='products-list'>
<ProductComponent />
</div>
</div>
)
}
export default ProductList
Error message appears on the console of the deployed app :
ProductList.js:21 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'data')
if(response.data.Search){
dispatch(setProducts(response.data.Search));
}
Try to check your response first.
I think you may have to prove catch error here. Adding else statement in case of response.data.Search is undefined or use response?.data.Search
Most browsers will block insecure requests (http) made from secure sites (https).
Change http://www.omdbapi.com/ to https://www.omdbapi.com/
Related
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
Error:
Compiled with problems:X
ERROR in ./src/App.js 8:0-63
Module not found: Error: Can't resolve '.src/components/NewsCards/NewsCards.js' in '/Users/admin/Desktop/ALAN_AI_NEWS APP/myaiproject/src'
ERROR
src/App.js
Line 7:45: 'useState' is not defined no-undef
Search for the keywords to learn more about each error.
Code:
import React, { useEffect } from 'react';
import alanBtn from '#alan-ai/alan-sdk-web';
import NewsCards from '.src/components/NewsCards/NewsCards.js';
const alanKey = '0f881486602df260f78c6dd18ef0cc6e2e956eca572e1d8b807a3e2338fdd0dc/stage';
const App = () => {
const [newsArticles, setNewsArticles] = useState ([]);
useEffect(() => {
alanBtn({
key: alanKey,
onCommand: ({ command, articles}) => {
if(command === 'newHeadlines') {
setNewsArticles(articles);
// Call the client code that will react to the received command
}
}
})
}, [])
return (
<div>
<h1>Alan AI News Application</h1>
<NewsCards articles={newsArticles} />
</div>
);
}
export default App;
Attached code above, pelase help solve this error
Please import useState hook as well
import React, { useEffect, useState } from 'react';
import alanBtn from '#alan-ai/alan-sdk-web';
const alanKey = '0f881486602df260f78c6dd18ef0cc6e2e956eca572e1d8b807a3e2338fdd0dc/stage';
function NewsCards(props) {
return (
<div>
// your component content
</div>
)
}
export const App = (props) => {
const [newsArticles, setNewsArticles] = useState([]);
useEffect(() => {
alanBtn({
key: alanKey,
onCommand: ({ command, articles}) => {
if(command === 'newHeadlines') {
setNewsArticles(articles);
// Call the client code that will react to the received command
}
}
})
}, [])
return (
<div className='App'>
<h1>Hello React.</h1>
<NewsCards articles={newsArticles} />
</div>
);
}
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.
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.
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>
);
}