Data lost in switch case reactjs - reactjs

I send data to another file with this:
import TropheeNameBlock from "../media-components/trophee-name-block"
<TropheeNameBlock currentUser={currentUser} userGender={userGender} />
I receive data from another file on the variable currentUser and userGender
I use a switch case to display an icon.
I have put a console.log(currentUser) the variable currentUser contain a Json like this:
{
"id":"4a1d-aeeb-a54ede02e90c",
"firstName":"MyFirstname",
"lastName":"MyLastname",
"gender":0,
"birthDate":"2021-08-05T15:43:00+02:00",
"phone":"000000",
"email":"myemail#mail.com",
"optin":true,
"language":"en-EN",
"country":"EN",
"streetName":"myStreetName",
"houseNumber":"",
"houseNumberExt":null,
"postalCode":"",
"city":"",
"idlsm":null,
"cars":[
"/cars/3854f416b36c",
"/cars/901cf0124e39"
],
"status":1,
"countOfUserReward":0,
"countOfEmailToRead":1,
"subscriptionDate":"2021-08-05T15:43:00+02:00",
"deletionDate":null,
"validationDate":"2021-08-05T17:15:55+02:00",
"lastUpdateDate":null,
"newPasswordRequestAt":"2021-08-05T17:15:55+02:00",
"newPasswordRequestToken":"TOKEN",
"events":[
"/car_events/b1ae-dbc2558f83c0",
"/car_events/802a-0d869bb7422d"
],
"carRemoveHistories":[
],
"rewards":[
],
"dealer":"4682-9223-df3cf582a883",
"particleName":"",
"reminderChannelNotification":false,
"reminderChannelSMS":false,
"reminderChannelEmail":true,
"offerChannelNotification":false,
"offerChannelSMS":true,
"offerChannelEmail":false,
"welcomeTimeline":true,
"welcomeRewards":true,
"contacts":[
],
"nissanCards":[
],
"source":"dealer_platform",
"medium":null,
"campaign":null,
"boardingFinishDate":null,
"rewardsAccessEndDate":null,
"scheduledDeletionDate":null,
"exportedToLsm":false,
"oldDealer":0,
"onboardedBy":"Onboarder",
"licencePlate":"ABC123"
}
My code with the switch case is like this:
import React from "react"
import {useTranslation} from 'react-i18next';
const TropheeNameBlock = ({currentUser, userGender}) => {
const {t} = useTranslation();
return(
<>
{(() => {
switch (currentUser.status) {
case 1:
return (<span className="icon-win icon-win-text"><span className="path1"></span><span className="path2"></span><span className="path3"></span><span className="text">{t('generic.status_level.' + currentUser.status)}</span></span>);
case 2:
return (<span className="icon-win icon-win-text silver"><span className="path1"></span><span className="path2"></span><span className="path3"></span><span className="text">{t('generic.status_level.' + currentUser.status)}</span></span>);
case 3:
return (<span className="icon-win icon-win-text gold"><span className="path1"></span><span className="path2"></span><span className="path3"></span><span className="text">{t('generic.status_level.' + currentUser.status)}</span></span>);
case 4:
return (<span className="icon-win icon-win-text platinum"><span className="path1"></span><span className="path2"></span><span className="path3"></span><span className="text">{t('generic.status_level.' + currentUser.status)}</span></span>);
}
})()}
<h3 className="pt-3 mb-2">{userGender} {currentUser.lastName}</h3>
</>
)
}
export default TropheeNameBlock
In my Json I would like to access in my field status.
In this case when I do a currentUser.status the variable are empty.
I have try to use a console.log(currentUser.status) inside the switch case like this:
switch (currentUser.status) {
case 1:
console.log(currentUser.status);
return (<span className="icon-win icon-win-text"><span className="path1"></span><span className="path2"></span><span className="path3"></span><span className="text">{t('generic.status_level.' + currentUser.status)}</span></span>);
But the console log is not display on the console because I think it don't enter to the switch case.
The main file:
The call API to get currentUser:
useEffect(() => {
UserService.getMeUserId({
"id": user.id,
"token": localStorage.getItem('token')
}).then( (resUser) => {
localStorage.setItem('currentUser', JSON.stringify(resUser.data.user));
setCurrentUser(localStorage.getItem('currentUser'));
})
)}
Here the code where I call the file TropheeNameBlock
const content = () => {
return(
<div class="row p-4">
<div class='col-md-12'>
<div class='p-2'>
{t('Back to client list')}
</div>
</div>
<div className="col-lg-4 d-none d-lg-block p-4 without-arrow">
<div className="status-container status-bronze white-container py-3 px-3 mb-3">
<TropheeNameBlock currentUser={currentUser} userGender={userGender} />
<hr />
<h3 className="mb-2">{t('my_profil.rewards_history')}</h3>
<RewardBlock currentUser={currentUser} />
</div>
<h3 className="text-uppercase">{t('my_profil.my_dealer.title')}</h3>
<div className="white-container py-2 px-3 mb-3">
<ul className="list-link-picto">
<li className="mb-0 py-3 w-100"><a to="/profile/my-dealer" state={{id: currentDealer.id}} className="my-dealer"><span className="icon-dealer-favorite icon"></span><h3 className="mb-0">{currentDealer.name}</h3></a></li>
</ul>
</div>
<h3 className="text-uppercase">{t('my_profil.my_vehicles')}</h3>
<div className="white-container py-0 px-3 mb-3">
<ul className="list-link-picto">
{ getCarsMedia()}
</ul>
</div>
</div>
<div class="col-lg-8 p-4">
<div className="white-container">
<h1 className="text-uppercase with-border-top with-border-bottom fs-20">{t('timeline.title')}</h1>
<p>{t('timeline.description')}</p>
<div className="d-flex align-items-center justify-content-between">
{getCars()}
</div>
<hr className="mt-2" />
{getEvents()}
</div>
</div>
</div>
)
};
let userGender = '';
if(currentUser) {
userGender = t('generic.forms.form_options.user_title.'+ currentUser.gender);
}
return(
<div className="wrapper">
<div className="container">
<main>
<header className="header py-2">
<div className="container d-flex align-items-center">
<img src={logoNissanNow} alt="Nissan Now" width="160" className="mr-auto"/>
<span className="dark-red cursor-pointer" onClick={() => logout()}><span
className="icon-logout-2 icon align-middle"></span>{t('Logout')}</span>
</div>
</header>
<BodyClass name="large-wrapper" />
{content()}
</main>
<footer className="d-flex justify-content-around d-md-block text-center footer">
{/* <Link to="#" className="mx-md-4" onClick={(e) => toggleModale(e)}>{intl.formatMessage({id: "footer.terms"})}</Link> */}
</footer>
</div>
</div>
)
};
Do you know why the data on currentUser are lost inside the switch case ?
Thanks you

I have found the solution.
I needed to use Json.Parse because I have stringify my data before
setCurrentUser(JSON.parse(localStorage.getItem('currentUser')));

Related

Line 18:19: 'value' is missing in props validation

I have this register page and it keeps showing me this error "Line 18:19:'value' is missing in props validation":
const Register = () =>{
const [value, setMyValue] = useState()
This function shows up a component based on the choice of the user that happens in the select tag
const Choice = ({ value }) =>{
if (value === "true"){
return <Employee />
}else{
return <Employer />
}
}
return(
<div>
<Navbar />
<div className="container-xxl bg-primary page-header">
<div className="container text-center">
<h1 className="text-white animated zoomIn">Sign Up</h1>
<nav aria-label="breadcrumb">
</nav>
</div>
</div>
<div className="container-xxl py-5" id="contact">
<div className="container">
<div className="mx-auto text-center wow fadeInUp" data-wow-delay="0.1s" style=
{{maxWidth: 600}}>
<div className="d-inline-block border rounded-pill text-primary px-4 mb-2">Sign Up
As</div>
<select onChange={(e)=>{setMyValue(e.target.value)}} className="form-select" aria-
label="Default select example">
<option value="false">Employer</option>
<option value="true">Employee</option>
</select>
<h2 className="mb-5 mt-4">Sign Up to find the best employees</h2>
</div>
<div>
<Choice value={ value } />
</div>
</div>
</div>
</div>
)
}
And this is the line 18 by the way:
const Choice = ({ value }) =>{
Maybe the problem could be 2 brackets in line 7?
if (value === "true"){
return <Employee />
}else{
return <Employer />
}

reactJS doesn't render the data after being fetched in useEffect hook

I have an API using axios which will fetch a list of products. I have called it inside useEffect() hook with [] as the second argument. I check the data before running into return command of the functional component and the data is there, but my ProductCard component are not rendered. Could you please help me with this?
FeaturedProducts.js
const FeaturedProducts = (props) => {
const [productList, setProductList] = useState([]);
// const productList = useSelector(productListSelector);
useEffect(async () => {
let rs = await fetchFeaturedProducts();
setProductList(rs);
}, []);
console.log(productList);
return (
<div className="container-fluid pt-5">
<div className="text-center mb-4">
<h2 className="section-title px-5"><span className="px-2">Featured</span></h2>
</div>
<div className="row px-xl-5 pb-3">
{
productList.map(product => {
<ProductCard id={product.id} name={product.name} price={product.price} img="abc"/> // need img={product.img}
})
}
</div>
</div>
);
}
export default FeaturedProducts;
fetchFeaturedProducts()
const fetchFeaturedProducts = async () => {
try {
let response = await AxiosClient.post("/product/search", {
searchType: "desc",
searchBy: "average_rating"
});
let data = response.data.data;
return data;
}
catch (error) {
raiseErrorMessages(error.response.data.errors);
return [];
}
}
ProductCard.js
const ProductCard = (props) => {
const detailUrl = "/product?id=" + toString(props.id);
return (
<div className="col-lg-3 col-md-6 col-sm-12 pb-1">
<div className="card product-item border-0 mb-4">
<div className="card-header product-img position-relative overflow-hidden bg-transparent border p-0">
<img className="img-fluid w-100" src={props.img} alt="" />
</div>
<div className="card-body border-left border-right text-center p-0 pt-4 pb-3">
<h6 className="text-truncate mb-3">{props.name}</h6>
<div className="d-flex justify-content-center">
<h6>{props.price}</h6>
{/* <h6 className="text-muted ml-2"><del>{props.price}</del></h6> */}
</div>
</div>
<div className="card-footer d-flex justify-content-between bg-light border">
<i className="fas fa-eye text-primary mr-1" />View Detail
<i className="fas fa-shopping-cart text-primary mr-1" />Add To Cart
</div>
</div>
</div>
)
}
export default ProductCard;
Thank you for your precious time.
that happens because you missed a return when you mapped your data
// .....
{
productList.map(product => {
return (<ProductCard id={product.id} name={product.name}
price={product.price} img="abc"/>) // need img=
{product.img}
})
}
or you can use ()
{
productList.map(product => (
<ProductCard id={product.id} name={product.name}
price={product.price} img="abc"/>) // need img=
{product.img})
}

React Router Dom Issue - localhost:3000/products to localhost:3000/products/2 is working fine but when I refresh page then I get some error in console

I have an Index.js where I am getting data via async function and sending data to ProductList Component and from ProductList Component I am sending an id onclick of product Image and then I get Product Detail Page a Single Product. I get Single Product with no issues but when I refresh then I get an error in console saying - Cannot read properties of undefined (reading 'filter') I have used REDUX.
INDEX.JS
import React, { useState, useEffect } from "react";
// import PageNotFound from "../other/page-not-found/PageNotFound";
import ProductList from "./product-list/ProductList";
import ProductFilter from "./product-filter/ProductFilter";
import ProductSearch from "./product-search/ProductSearch";
import Cart from "./cart/Cart";
// import MobileFilterModal from "./mobile-filter-modal/MobileFilterModal";
import { useDispatch, useSelector } from "react-redux";
import { setProductListData } from "../../redux/actions/product-list-actions/ProductListActions";
import Loading from "../other/loading/Loading";
import Skeleton from "../other/skeletons/Skeleton";
// import PageNotFound from "../other/page-not-found/PageNotFound";
const Index = () => {
const [isLoading, setIsLoading] = useState(true);
const dispatch = useDispatch();
const filters = useSelector(
(state) => state.productList.productListData.filters
);
const products = useSelector(
(state) => state.productList.productListData.products
);
// console.log(products);
useEffect(() => {
getProductsData();
}, []);
const getProductsData = async () => {
try {
const response = await fetch("http://localhost:8000/productListing");
const data = await response.json();
if (data) {
setIsLoading(false);
dispatch(setProductListData(data));
} else {
setIsLoading(true);
}
} catch (error) {
console.log(error);
}
};
// if (isLoading) {
// return <Loading loadingProductList={"products"} />;
// }
return (
<>
{filters && products && (
<main>
<div className="dvMain">
<div className="container-fluid">
<div className="row">
<div className="dvFilters col-lg-3 col-xl-2 d-none d-lg-block text-right">
<div className="sticky-top" style={{ top: "90px" }}>
{isLoading
? filters.map((filter) => {
return (
<Skeleton key={filter.id} filterId={filter.id} />
);
})
: filters &&
filters.map((filter) => {
return <ProductFilter key={filter.id} {...filter} />;
})}
</div>
</div>
<div className="dvProducts col-lg-6 col-xl-8">
<div className="row">
<div className="dvSearch col-sm-9 col-md-10 col-lg-12 mb-3">
{isLoading ? (
<Skeleton productSearch={"productSearch"} />
) : (
<ProductSearch />
)}
</div>
<div className="dvFilterMobile col-sm-3 col-md-2 d-lg-none text-center text-sm-right mb-3">
<a
href=""
className="btn bg-light w-100"
data-toggle="modal"
data-target="#mobileFiltersModal"
>
<i className="fa fa-filter"></i>Filter
</a>
</div>
</div>
<div className="row">
{isLoading
? products.map((product) => {
return (
<Skeleton key={product.id} productId={product.id} />
);
})
: products &&
products.map((product) => {
return <ProductList key={product.id} {...product} />;
})}
</div>
</div>
{isLoading ? <Skeleton cart={"cart"} /> : <Cart />}
</div>
</div>
</div>
</main>
)}
</>
);
};
export default Index;
PRODUCTLIST.JS
import React from "react";
import { Link } from "react-router-dom";
import "./productlist.css";
const ProductList = ({ id, img, pack, price, size, heading, description }) => {
// console.log(id, img, pack, price, size, heading, description);
// console.log(id, img, pack, price, size, heading, description);
return (
<>
<div className="col-6 col-md-4 col-lg-6 col-xl-3 mb-4">
<div className="border border-light shadow-sm p-1 h-100">
<div className="image">
<p className="packs">pack of 5</p>
<div className="bg-light text-center pt-2 pb-2 mb-1">
<Link className="d-inline-block" to={`/${id}`}>
<img src={img} className="img-fluid" alt={heading} />
</Link>
</div>
<h5 className="heading-5 text-center">{heading}</h5>
</div>
<div className="description d-flex justify-content-between mb-1">
<div className="paragraph">
<p>{size}</p>
</div>
<div className="paragraph mr-2">
<span>
<i className="fa fa-inr"></i>
<span>{price}</span>
</span>
</div>
</div>
<div className="addBtn text-center">
<button className="btn btn-white w-100" href="detail.html">
Add to Bag
</button>
</div>
</div>
</div>
</>
);
};
export default ProductList;
PRODUCTDETAIL.JS
import React, { useState, useEffect } from "react";
import Cart from "../cart/Cart";
import "./productdetail.css";
import Loading from "../../other/loading/Loading";
import PageNotFound from "../../other/page-not-found/PageNotFound";
import { Link, useParams } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { setSelectedProduct } from "../../../redux/actions/product-detail-actions/ProductDetailActions";
const ProductDetail = () => {
const [isLoading, setIsLoading] = useState(true);
const { id } = useParams();
const dispatch = useDispatch();
const products = useSelector(
(state) => state.productList.productListData.products
);
const singleProduct = useSelector(
(state) => state.singleProduct.singleProduct
);
// console.log(id);
// console.log(products);
// console.log(singleProduct);
useEffect(() => {
getProductId();
}, []);
const getProductId = () => {
window.scrollTo(0, 0);
// localStorage.setItem("setProducts", JSON.stringify(products));
// let getProducts = JSON.parse(localStorage.getItem("setProducts"));
products ? setIsLoading(false) : setIsLoading(true);
let singleProduct = [];
singleProduct = products.filter((product) => {
return product.id === parseInt(id);
});
// console.log(singleProduct);
dispatch(setSelectedProduct(singleProduct));
};
if (isLoading) {
return <Loading loadingProductDetail={"product detail"} />;
}
return (
<>
{singleProduct && (
<main>
<div className="dvMain">
<div className="container">
<div className="row">
{singleProduct ? (
singleProduct.map((product) => {
const {
id,
img,
heading,
description,
category,
price,
size,
} = product;
return (
<div key={id} className="col-lg-9">
<div className="row">
<div className="dvProducts col-12">
<div className="row">
<div className="dvBack col-12">
<Link
to="/products"
className="mb-1 d-inline-block"
>
<i className="fa fa-angle-left"></i>
<span> Back</span>
</Link>
</div>
<div className="col-12">
<div className="row">
<div className="col-12 col-md-6 col-xl-4 mb-3">
<div className="border border-light shadow-sm p-1 h-100 d-flex justify-content-center align-items-center">
<div className="bg-light text-center h-100">
<a className="d-inline-block h-100">
<img
src={img}
className="img-fluid"
alt={heading}
/>
</a>
</div>
</div>
</div>
<div className="col-12 col-md-6 col-xl-8 d-flex mb-3 mb-xl-0">
<div className="m-md-auto">
<div>
<h2 className="heading-2">{heading}</h2>
</div>
<div className="mb-2">
<i className="fa fa-star text-warning d-inline-block"></i>
<i className="fa fa-star text-warning d-inline-block"></i>
<i className="fa fa-star text-warning d-inline-block"></i>
<i className="fa fa-star-o text-warning d-inline-block"></i>
<i className="fa fa-star-o text-warning d-inline-block"></i>
</div>
<div className="mb-3">
<p className="paragraph">
{description}
</p>
</div>
<div className="d-flex mb-3">
<div className="mr-2">
<h5 className="heading-5 d-inline-block mb-1 mr-1">
Size:
</h5>
<span className="paragraph d-inline-block">
{size}
</span>
</div>
<div className="mr-2 ml-2">
<h5 className="heading-5 d-inline-block mb-1 mr-1">
Category:
</h5>
<span className="paragraph d-inline-block">
{category}
</span>
</div>
<div className="ml-2">
<h5 className="heading-5 d-inline-block mb-1 mr-1">
Price:
</h5>
<span className="paragraph d-inline-block">
<i className="fa fa-inr"></i>
<span className="d-inline-block">
{price}.00
</span>
</span>
</div>
</div>
<div>
<button
className="btn btn-black"
href="/-"
>
Add to Bag
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div className="dvTabs col-12 mt-4">
<div className="row">
<div className="col-12">
<div className="row">
<div className="col-12">
<ul
className="nav nav-tabs"
id="myTab"
role="tablist"
>
<li className="nav-item">
<a
className="heading-5 nav-link active"
id="description-tab"
data-toggle="tab"
href="#description"
role="tab"
aria-controls="description"
aria-selected="true"
>
Description
</a>
</li>
</ul>
</div>
</div>
<div
className="dvTabsContent tab-content row"
id="myTabContent"
>
<div
className="tab-pane fade show active py-3 col-12"
id="description"
role="tabpanel"
aria-labelledby="description-tab"
>
<div className="row">
<div className="col-12">
<div className="table-responsive">
<table className="table table-striped table-bordered">
<thead>
<tr>
<th
className="heading-5"
scope="col"
>
Details
</th>
<th
className="heading-5"
scope="col"
>
Weight
</th>
<th
className="heading-5"
scope="col"
>
1Glass 250ml
</th>
</tr>
</thead>
<tbody>
<tr>
<td>Amount per serving</td>
<td>250ml</td>
<td></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
})
) : (
<PageNotFound />
)}
<Cart id={id} />
</div>
</div>
</div>
</main>
)}
</>
);
};
export default ProductDetail;
APP.JS
import React from "react";
import "./App.css";
import { BrowserRouter, Switch, Route } from "react-router-dom";
import Homepage from "./containers/home-page/index";
import Header from "./containers/header/Header";
import Footer from "./containers/footer/Footer";
// import ProductListing from "./containers/products/product-list/ProductList";
import ProductDetail from "./containers/products/product-detail/ProductDetail";
import PageNotFound from "./containers/other/page-not-found/PageNotFound";
import Account from "./containers/account/index";
import Checkout from "./containers/checkout/Index";
import LoginModal from "./containers/auth/modal/login-modal/LoginModal";
import SignupModal from "./containers/auth/modal/signup-modal/SignupModal";
import MobileCartModal from "./containers/products/mobile-cart-modal/MobileCartModal";
import Index from "./containers/products";
const App = () => {
return (
<>
<BrowserRouter>
<Header />
<main>
<Switch>
<Route path="/" exact component={Homepage} />
<Route path="/products" component={Index} />
<Route path="/:id" children={<ProductDetail />} />
<Route path="/checkout" component={Checkout} />
<Route path="/account" component={Account} />
<Route path="*" component={PageNotFound} />
</Switch>
</main>
<Footer />
<LoginModal />
<SignupModal />
<MobileCartModal />
</BrowserRouter>
</>
);
};
export default App;
PRODUCTDETAILACTIONS.JS
export const setSelectedProduct = (product) => {
return {
type: "SET_SELECTED_PRODUCT",
payload: product,
};
};
PRODUCTDETAILREDUCER.JS
const initialState = {
singleProduct: [],
};
export const productDetailReducer = (state = initialState, action) => {
switch (action.type) {
case "SET_SELECTED_PRODUCT":
return {
...state,
singleProduct: action.payload,
};
default:
return state;
}
};
REDUCER INDEX.JS
import { combineReducers } from "redux";
import { aboutUsReducer } from "./aboutus-reducers/AboutUsReducers";
import { footerReducer } from "./footer-reducers/FooterReducer";
import { headerReducer } from "./header-reducers/headerReducer";
import { mainSliderReducer } from "./homepage-reducers/mainSliderReducer";
import { youtubeReducer } from "./homepage-reducers/YoutubeReducer";
import { productDetailReducer } from "./product-detail/ProductDetailReducer";
import { productListReducer } from "./product-list-reducers/ProductListReducer";
import { productSliderData } from "./productslider-reducers/ProductSliderReducer";
import { teamReducer } from "./team-reducers/TeamReducers";
const rootReducer = combineReducers({
header: headerReducer,
mainSlider: mainSliderReducer,
youtube: youtubeReducer,
aboutUs: aboutUsReducer,
productSlider: productSliderData,
team: teamReducer,
footer: footerReducer,
productList: productListReducer,
singleProduct: productDetailReducer,
});
export default rootReducer;
STORE.JS
import { createStore } from "redux";
import rootReducer from "./reducers/index";
const store = createStore(
rootReducer,
{},
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
export default store;
PRODUCTLISTACTIONS.JS
export const setProductListData = (data) => {
return {
type: "SET_PRODUCT_LIST_DATA",
payload: data,
};
};
PRODUCTLISTREDUCER.JS
const initialState = {
productListData: {},
};
export const productListReducer = (state = initialState, action) => {
switch (action.type) {
case "SET_PRODUCT_LIST_DATA":
return {
...state,
productListData: action.payload,
};
default:
return state;
}
};
DB.JSON
I am fetching productListing from json file which look like this
From what I can see, the ProductDetails component is missing a dependency on the id route param to select the correct products to filter, and I am assuming that since the index file is fetching and populating the store each time it mounts that perhaps the initial products state is null, undefined, or some other non-array value that is missing the filter method.
Add the missing id route param to the useEffect hook's dependency array so products are fetched when the route changes.
const { id } = useParams();
...
useEffect(() => {
getProductId(id);
}, [id]);
Since it appears that products is potentially undefined, i.e. falsey, you should account for then when attempting to filter the array. Provide a fallback empty array to filter from if products is falsey.
const getProductId = (id) => {
window.scrollTo(0, 0);
products ? setIsLoading(false) : setIsLoading(true);
const singleProduct = (products || []).filter((product) => {
return product.id === parseInt(id);
});
dispatch(setSelectedProduct(singleProduct));
};
You didn't include any of your Redux code (i.e. actions/reducers/store configuration) but a suggestion is to always provide a consistent state invariant. For example, always returning an array of products and using the array length and some "isLoading" state to determine when it's safe to filter the state. At a minimum, if it's guaranteed that products is always an array then all array methods will always work as expected, regardless of where the app is in its lifecycle and loading data/state.
Hey I found this solution. I fetched products through async function instead of getting products back from useSelector. Please check ProductDetail Component below.
PRODUCTDETAIL.JS
import React, { useState, useEffect } from "react";
import Cart from "../cart/Cart";
import "./productdetail.css";
import Loading from "../../other/loading/Loading";
import PageNotFound from "../../other/page-not-found/PageNotFound";
import { Link, useParams } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { setSelectedProduct } from "../../../redux/actions/product-detail-actions/ProductDetailActions";
const ProductDetail = () => {
const [loading, setLoading] = useState(true);
const { id } = useParams();
const dispatch = useDispatch();
const singleProduct = useSelector(
(state) => state.singleProduct.singleProduct
);
useEffect(() => {
getProductListingData();
}, []);
const getProductListingData = async () => {
try {
const response = await fetch("http://localhost:8000/productListing");
const data = await response.json();
if (data) {
setLoading(false);
getProductID(data.products);
} else {
// setProducts("PRODUCT LISTING DATA NOT FOUND");
setLoading(true);
console.log("PRODUCT LISTING DATA NOT FOUND");
}
} catch (error) {
console.log(error);
}
};
const getProductID = (products) => {
window.scroll(0, 0);
let singleProduct = [];
singleProduct = products.filter((item) => {
return item.id === parseInt(id);
});
dispatch(setSelectedProduct(singleProduct));
};
if (loading) {
return <Loading loadingProductDetail="Loading Product Details" />;
}
console.log(id);
console.log(singleProduct);
return (
<>
<main>
<div className="dvMain">
<div className="container">
<div className="row">
{singleProduct.length > 0 &&
singleProduct.map((product) => {
const {
id,
img,
heading,
description,
pack,
price,
size,
category,
detailsTable,
} = product;
return (
<div key={id} className="col-lg-9">
<div className="row">
<div key={id} className="dvProducts col-12">
<div className="row">
<div className="dvBack col-12">
<Link
to="/products"
className="mb-1 d-inline-block"
>
<i className="fa fa-angle-left"></i>
<span> Back</span>
</Link>
</div>
<div className="col-12">
<div className="row">
<div className="col-12 col-md-6 col-xl-4 mb-3">
<div className="border border-light shadow-sm p-1 h-100 d-flex justify-content-center align-items-center">
<div className="bg-light text-center h-100">
<a className="d-inline-block h-100">
<img
src={img}
className="img-fluid"
alt={heading}
/>
</a>
</div>
</div>
</div>
<div className="col-12 col-md-6 col-xl-8 d-flex mb-3 mb-xl-0">
<div className="m-md-auto">
<div>
<h2 className="heading-2">{heading}</h2>
</div>
<div className="mb-2">
<i className="fa fa-star text-warning d-inline-block"></i>
<i className="fa fa-star text-warning d-inline-block"></i>
<i className="fa fa-star text-warning d-inline-block"></i>
<i className="fa fa-star-o text-warning d-inline-block"></i>
<i className="fa fa-star-o text-warning d-inline-block"></i>
</div>
<div className="mb-3">
<p className="paragraph">{description}</p>
</div>
<div className="d-flex mb-3">
<div className="mr-2">
<h5 className="heading-5 d-inline-block mb-1 mr-1">
Pack:
</h5>
<span className="paragraph d-inline-block">
{pack}
</span>
</div>
<div className="mr-2">
<h5 className="heading-5 d-inline-block mb-1 mr-1">
Size:
</h5>
<span className="paragraph d-inline-block">
{size}
</span>
</div>
<div className="mr-2 ml-2">
<h5 className="heading-5 d-inline-block mb-1 mr-1">
Category:
</h5>
<span className="paragraph d-inline-block">
{category}
</span>
</div>
<div className="ml-2">
<h5 className="heading-5 d-inline-block mb-1 mr-1">
Price:
</h5>
<span className="paragraph d-inline-block">
<i className="fa fa-inr"></i>
<span className="d-inline-block">
{price}.00
</span>
</span>
</div>
</div>
<div>
<button
className="btn btn-black"
href="/-"
>
Add to Bag
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div className="dvTabs col-12 mt-4">
<div className="row">
<div className="col-12">
<div className="row">
<div className="col-12">
<ul
className="nav nav-tabs"
id="myTab"
role="tablist"
>
<li className="nav-item">
<a
className="heading-5 nav-link active"
id="description-tab"
data-toggle="tab"
href="#description"
role="tab"
aria-controls="description"
aria-selected="true"
>
Description
</a>
</li>
</ul>
</div>
</div>
<div
className="dvTabsContent tab-content row"
id="myTabContent"
>
<div
className="tab-pane fade show active py-3 col-12"
id="description"
role="tabpanel"
aria-labelledby="description-tab"
>
<div className="row">
<div className="col-12">
<div className="table-responsive">
<table className="table table-striped table-bordered">
<thead>
<tr>
<th
className="heading-5"
scope="col"
>
Details
</th>
<th
className="heading-5"
scope="col"
>
Weight
</th>
<th
className="heading-5"
scope="col"
>
1Glass 250ml
</th>
</tr>
</thead>
<tbody>
<tr>
<td>Amount per serving</td>
<td>250ml</td>
<td></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
})}
<Cart id={id} />
</div>
</div>
</div>
</main>
</>
);
};
export default ProductDetail;

showing the applicants of a job in reactjs using id

Iam trying to make a react application whereby users are applying for a job and also creating a report that will show the profile of the users who have applied for the job. Iam welcome to any ideas that can be given to me since I would like to have a logic on how to implement that.
Here is my code below:
DriverCard.js
import React from "react";
import member2 from "../../../dist/images/user2.png";
const DriverCard = ({cardValues}) => {
return (
<>
<div className="col-lg-3 col-md-3 col-sm-4 col-6 p-0 mb-5">
<div className="text-center">
<div className="mb-2">
<img
src={cardValues ? `${cardValues.location.title}` : member2}
className="rounded-circle"
height="85px"
width="85px"
alt="members"
/>
</div>
<h6 className="mb-0 textHeading">
{cardValues ? cardValues.name : `John Doe`}
</h6>
<span className="text-muted textStyle"> #JohntheD 5h</span>
<hr
style={{
width: "50%",
marginTop: 4,
marginBottom: 1,
}}
/>
<h6 className="textStyle mt-1">
{cardValues ? `${cardValues.licenseAge} +years licence` : `NA`}
</h6>
<h6 className="textStyle">
{cardValues ? `${cardValues.experience} +years experience` : `NA`}
</h6>
</div>
</div>
</>
);
};
export default DriverCard;
This is the report file that is suppossed to show the jobcard and the profile for the applicants.
import React, { useEffect, useState } from "react";
import {useHistory} from "react-router-dom";
import map from "lodash/map"
import { getSpecificJobCard } from "../../Api/index";
import arrowBack from "../../dist/images/arrowBack.svg";
import DriverCard from "./Job_Components/DriverCard";
import JobCardDetails from "./Job_Components/JobCardDetails";
import NextPageButtons from "../Main/DashBoard_Buttons/NextPageButtons";
const JobDetails = ({jobpostId}) => {
const [jobCard, setjobCard] = useState([]);
const history = useHistory();
console.log("param val",jobpostId);
useEffect(() => {
(async () => {
let jobCardRespData = await getSpecificJobCard(jobpostId);
setjobCard(jobCardRespData);
console.log("jobcard response:", jobCardRespData);
})();
}, []);
console.log("resp list ----- ", jobCard);
return (
<div className="">
<div className="col-md-10 m-auto">
<span style={{ cursor: "pointer" }} className="">
<img src={arrowBack} alt="" className="img-fluid" />
</span>
<div className="row">
<div className="col-lg-4 mt-5">
<div className="row">
{}
<JobCardDetails job={jobCard} />
</div>
</div>
<div className="col-lg-8 mt-5">
<div className="row">
<DriverCard/>
{/* <DriverCard /> */}
</div>
</div>
</div>
<div className="row">
<div className="col-lg-12">
<div className="row">
</div>
</div>
</div>
</div>
<div className="col-lg-12 my-3 border-top">
<NextPageButtons/>
</div>
</div>
);
};
export default JobDetails;

I am trying to import a different product list from an array named clothingproducts

I have three arrays one with all of the items and the other two with specific items. When I change the array name in context it works but when i create another context file with the same code (contextc) I get this error TypeError: Cannot read property 'products' of undefined
return value.products.map(product => {
import React, { Component } from "react";
import Product from "./Product";
import { ProductConsumer } from "../contextc";
export default class Productlist extends Component {
render() {
return (
<React.Fragment>
<header className="bg py-5 mb0 container-fluid clothing border-bottom border-danger">
<div className="container h-100">
<div className="row h-100 align-items-center">
<div className="col-lg-12">
<h1 className="display-4 text-white mt-5 mb-2 text-center">
Clothing
</h1>
<p className="lead mb-5 text-white-50 text-center">
Our latest Releases.
</p>
</div>
</div>
</div>
</header>
<div className="py-0 ">
<div className="container">
<div className="row">
<ProductConsumer>
{value => {
return value.products.map(product => {
return <Product key={product.id} product={product} />;
});
}}
</ProductConsumer>
</div>
</div>
</div>
</React.Fragment>
);
}
}
this is happening because value is undefined.

Resources