I am storing webpage content as a byte[] logo and an html body in database. When I click to load a specific category group, I get "Maximum call stack size exceeded" if the logo image is too large (in this case > 200kB). But if I store the same image as a base64 tagged image inside the html body, it doesn't fail. I've searched and searched but I cant find an explanation for this behavior. I searched for other answers. I changed the way I store the image. I tested different sizes. I expect the logo to load async regardless of size. I'm newer to React; any guidance would be appreciated.
Here is the MemberBenefit object:
export default interface MemberBenefit {
Id: string;
Name: string;
CategoryId: string;
Logo: ImageFile;
Detail: string;
}
export interface MemberBenefitCategory{
id: string;
Name: string;
ParentId: string;
}
export interface ImageFile{
data: number[];
contentType: string;
fileName: string;
}
The code where the logo and body are rendered is here:
<Accordion.Collapse eventKey={benefit.Id.toString()}>
<Card.Body>
{benefit.Logo &&
<>
<img style={{width:"100%"}} src={"data: "+benefit.Logo.contentType+"; base64," + btoa(String.fromCharCode.apply(null, benefit.Logo.data)) }></img>
</>
}
<section
className="not-found-controller"
dangerouslySetInnerHTML={{ __html: benefit.Detail }}
/>
</Card.Body>
</Accordion.Collapse>
Here is the whole TSX file for reference. I'm sure I am being very inefficient in many places, so I appreciate all the constructive feedback.
import React, { useEffect, useState } from "react"
import {Container, Row, Col, Breadcrumb, Button, Card, Accordion} from "react-bootstrap"
import {Redirect, Link} from "react-router-dom"
import ClientApi from "../../api/ClientApi"
import {ContainsAuthExpiredError} from "../../models/ErrorDetail"
import BenefitGroupPicker from "../../views/benefits/BenefitGroupPicker"
import PageHeading from "../../views/PageHeading"
import { FontAwesomeIcon } from '#fortawesome/react-fontawesome'
import { library } from '#fortawesome/fontawesome-svg-core'
import MemberBenefit, { MemberBenefitCategory } from "../../models/MemberBenefit"
import { faBriefcase, faCar, faCarrot, faCircle, faDollarSign, faFaceGrinWide, faHeartPulse, faHouseChimney, faPlaneUp, faSailboat, faSquare, faWrench } from "#fortawesome/free-solid-svg-icons"
const Index: React.FC = () => {
const {errors, payload} = ClientApi.Account.UseAccountOverview()
const accountOverview = payload
const redirectToDisabled = accountOverview?.MembershipSummary.IsDelinquent ?? false
const [categories, set_categories] = useState<MemberBenefitCategory[] >([]);
const [selectedParentCategoryIndex, set_selectedParentCategoryIndex] = useState<number | null>(null);
const [loadedMemberBenefits, set_loadedMemberBenefits] = useState<MemberBenefit[] | null>(null);
useEffect(() => {
let mounted = true
const fetchData = async () => {
var [_getCategories, _error] = await ClientApi.Benefits.GetMemberBenefitCategories();
if (mounted) {
if (_error.length > 0) {
//set_benefitsLoadingErrors(allErrors)
} else {
set_categories(_getCategories ?? [])
}
}
}
fetchData()
return () => {
mounted = false
}
}, [])
const LoadParent = async (parentCategoryId:string) =>{
var [_getMemberBenefits, _error] = await ClientApi.Benefits.GetMemberBenefits(parentCategoryId ?? 0);
set_loadedMemberBenefits(_getMemberBenefits)
set_selectedParentCategoryIndex(categories.findIndex(category=> category.id == parentCategoryId))
}
// maybe fold these into 1 redirection checker function?
if (ContainsAuthExpiredError(errors)) {
return <Redirect to='/login' />
}
if (redirectToDisabled) {
return <Redirect to='/memberBenefits/Disabled' />
}
if (accountOverview && accountOverview.MembershipSummary.IsTerminated) {
return <Redirect to='/myMembership/PayDues' />
}
return (
<div className='component_BenefitsIndex'>
<PageHeading>
Member <b>Benefits</b>
</PageHeading>
<Container className='pageContent'>
<div className="d-lg-none d-xl-none ">
{selectedParentCategoryIndex == null &&
<>
<div id="benefitsPicker" style={{marginTop:"15px"}}>
<Row style={{textAlign:"center",lineHeight:"48px"}}>
<Col>
<button onClick={() => LoadParent("5")}>
<span className="fa-layers MemberBenefitsNav" style={{width:"6em"}}>
<FontAwesomeIcon style={{color:"#FF671E"}} icon={faCircle} size="4x" />
<FontAwesomeIcon style={{color:"white"}} icon={faWrench} size='2x'/>
</span>
<div>Equipment</div>
</button>
</Col>
<Col>
<button onClick={() => LoadParent("1")}>
<span className="fa-layers MemberBenefitsNav" style={{width:"6em"}} >
<FontAwesomeIcon style={{color:"#FF671E"}} icon={faCircle} size="4x" />
<FontAwesomeIcon style={{color:"white", fontSize:"30px", top:"-15px", left:"-15px"}} icon={faSailboat}/>
<FontAwesomeIcon style={{color:"#FF671E", fontSize:"25px",top:"10px", left:"10px"}} icon={faSquare} />
<FontAwesomeIcon style={{color:"#FF671E", fontSize:"35px", top:"10px", left:"10px"}} icon={faCar} />
<FontAwesomeIcon style={{color:"#FF671E", width:"100px", height:"10px", top:"15px", left:"-7px"}} icon={faSquare} />
<FontAwesomeIcon style={{color:"white", fontSize:"30px", top:"10px", left:"10px"}} icon={faCar} />
</span>
<div>Auto/Boat</div>
</button>
</Col>
<Col>
<button onClick={() => LoadParent("2")}>
<span className="fa-layers MemberBenefitsNav" style={{width:"6em"}} >
<FontAwesomeIcon style={{color:"#FF671E"}} icon={faCircle} size="4x" />
<FontAwesomeIcon style={{color:"white"}} icon={faPlaneUp} size='2x'/>
</span>
<div>Travel</div>
</button>
</Col>
</Row>
<Row style={{textAlign:"center",lineHeight:"48px"}}>
<Col>
<button onClick={() => LoadParent("6")}>
<span className="fa-layers MemberBenefitsNav" style={{width:"6em"}} >
<FontAwesomeIcon style={{color:"#FF671E"}} icon={faCircle} size="4x" />
<FontAwesomeIcon style={{color:"white"}} icon={faDollarSign} size='2x'/>
</span>
<div>Financial</div>
</button>
</Col>
<Col>
<button onClick={() => LoadParent("3")}>
<span className="fa-layers MemberBenefitsNav" style={{width:"6em"}} >
<FontAwesomeIcon style={{color:"#FF671E"}} icon={faCircle} size="4x" />
<FontAwesomeIcon style={{color:"white"}} icon={faHouseChimney} size='2x'/>
</span>
<div>Home/Farm</div>
</button>
</Col>
<Col>
<button onClick={() => LoadParent("7")}>
<span className="fa-layers MemberBenefitsNav" style={{width:"6em"}} >
<FontAwesomeIcon style={{color:"#FF671E"}} icon={faCircle} size="4x" />
<FontAwesomeIcon style={{color:"white"}} icon={faHeartPulse} size='2x'/>
</span>
<div>Health</div>
</button>
</Col>
</Row>
<Row style={{textAlign:"center",lineHeight:"48px"}}>
<Col>
<button onClick={() => LoadParent("4")}>
<span className="fa-layers MemberBenefitsNav" style={{width:"6em"}} >
<FontAwesomeIcon style={{color:"#FF671E"}} icon={faCircle} size="4x" />
<FontAwesomeIcon style={{color:"white"}} icon={faFaceGrinWide} size='2x'/>
</span>
<div style={{marginTop: "11px",lineHeight: "25px"}}>Attractions/<br/>Sports</div>
</button>
</Col>
<Col>
<button onClick={() => LoadParent("8")}>
<span className="fa-layers MemberBenefitsNav" style={{width:"6em"}} >
<FontAwesomeIcon style={{color:"#FF671E"}} icon={faCircle} size="4x" />
<FontAwesomeIcon style={{color:"white"}} icon={faBriefcase} size='2x'/>
</span>
<div>Career</div>
</button>
</Col>
<Col>
<button onClick={() => LoadParent("9")}>
<span className="fa-layers MemberBenefitsNav" style={{width:"6em"}} >
<FontAwesomeIcon style={{color:"#FF671E"}} icon={faCircle} size="4x" />
<FontAwesomeIcon style={{color:"white"}} icon={faCarrot} size='2x'/>
</span>
<div>FAMA</div>
</button>
</Col>
</Row>
</div>
</>
}
{selectedParentCategoryIndex != null &&
<>
<button onClick={()=>set_selectedParentCategoryIndex(null)}>back</button>
<div className='blockNavContent'>
<h2>{categories[selectedParentCategoryIndex].Name}</h2>
{
categories.filter(category=>{return category.ParentId == categories[selectedParentCategoryIndex].id}).map(category=>
<Accordion key={category.id+"sub"}>
<Card>
<Card.Header>
{/* This was Accordion.Toggle in old version */}
<Accordion.Toggle as={Button} variant="link" eventKey={category.id.toString()}>
{category.Name}
</Accordion.Toggle>
</Card.Header>
<Accordion.Collapse eventKey={category.id.toString()}>
<Card.Body>
{
loadedMemberBenefits?.filter(benefit=>benefit.CategoryId == category.id.toString()).map(benefit=>
<Accordion key={benefit.Id +"subbenefit"}>
<Card >
<Card.Header>
{/* This was Accordion.Toggle in old version */}
<Accordion.Toggle as={Button} variant="link" eventKey={benefit.Id.toString()}>
{benefit.Name}
</Accordion.Toggle>
</Card.Header>
<Accordion.Collapse eventKey={benefit.Id.toString()}>
<Card.Body>
{benefit.Logo &&
<>
<img style={{width:"100%"}} src={"data: "+benefit.Logo.contentType+"; base64," + btoa(String.fromCharCode.apply(null, benefit.Logo.data)) }></img>
</>
}
<section
className="not-found-controller"
dangerouslySetInnerHTML={{ __html: benefit.Detail }}
/>
</Card.Body>
</Accordion.Collapse>
</Card>
</Accordion>
)
}
</Card.Body>
</Accordion.Collapse>
</Card>
</Accordion>
)
}
{
loadedMemberBenefits?.filter(benefit=>benefit.CategoryId == categories[selectedParentCategoryIndex].id.toString()).map(benefit=>
<Accordion key={benefit.Id +"sub"}>
<Card >
<Card.Header>
{/* This was Accordion.Toggle in old version */}
<Accordion.Toggle as={Button} variant="link" eventKey={benefit.Id.toString()}>
{benefit.Name}
</Accordion.Toggle>
</Card.Header>
<Accordion.Collapse eventKey={benefit.Id.toString()}>
<Card.Body>
{benefit.Logo &&
<>
<img style={{width:"100%"}} src={"data: "+benefit.Logo.contentType+"; base64," + btoa(String.fromCharCode.apply(null, benefit.Logo.data)) }></img>
</>
}
<section
className="not-found-controller"
dangerouslySetInnerHTML={{ __html: benefit.Detail }}
/>
</Card.Body>
</Accordion.Collapse>
</Card>
</Accordion>
)
}
</div>
</>
}
</div>
<Row className="d-none d-lg-block">
<Col>
<div className="blockNavGrid">
<div className="blockNavsList">
{
categories.filter(category=>{return category.ParentId == ""}).map(category=>
<div key={category.id}>
<Button onClick={() => LoadParent(category.id)} >
{category.Name}
</Button>
</div>
)
}
</div>
{selectedParentCategoryIndex == null &&
<>
<div className='blockNavContent'>
<div style={{marginBottom: "48px"}}>
<img
src='https://apps.floridafarmbureau.com/_cdn/img/MembershipMeansMoreHeader.svg'
alt='Membership Means More'
/>
</div>
<p>
Membership with Florida Farm Bureau means that you are part of a
growing community of member families in Florida. Members, just
like you, advocate for agriculture and grow as better leaders in
our state through their membership. As a thank you for your
membership, you are provided with access to over 30 companies to
provide benefits and discounts.
</p>
<p>Click a section for more information. </p>
</div>
</>
}
{selectedParentCategoryIndex != null &&
<>
<div className='blockNavContent'>
<h2>{categories[selectedParentCategoryIndex].Name}</h2>
{
categories.filter(category=>{return category.ParentId == categories[selectedParentCategoryIndex].id}).map(category=>
<Accordion key={category.id+"sub"}>
<Card>
<Card.Header>
{/* This was Accordion.Toggle in old version */}
<Accordion.Toggle as={Button} variant="link" eventKey={category.id.toString()}>
{category.Name}
</Accordion.Toggle>
</Card.Header>
<Accordion.Collapse eventKey={category.id.toString()}>
<Card.Body>
{
loadedMemberBenefits?.filter(benefit=>benefit.CategoryId == category.id.toString()).map(benefit=>
<Accordion key={benefit.Id +"subbenefit"}>
<Card >
<Card.Header>
{/* This was Accordion.Toggle in old version */}
<Accordion.Toggle as={Button} variant="link" eventKey={benefit.Id.toString()}>
{benefit.Name}
</Accordion.Toggle>
</Card.Header>
<Accordion.Collapse eventKey={benefit.Id.toString()}>
<Card.Body>
{benefit.Logo &&
<>
<img style={{width:"100%"}} src={"data: "+benefit.Logo.contentType+"; base64," + btoa(String.fromCharCode.apply(null, benefit.Logo.data)) }></img>
</>
}
<section
className="not-found-controller"
dangerouslySetInnerHTML={{ __html: benefit.Detail }}
/>
</Card.Body>
</Accordion.Collapse>
</Card>
</Accordion>
)
}
</Card.Body>
</Accordion.Collapse>
</Card>
</Accordion>
)
}
{
loadedMemberBenefits?.filter(benefit=>benefit.CategoryId == categories[selectedParentCategoryIndex].id.toString()).map(benefit=>
<Accordion key={benefit.Id +"sub"}>
<Card >
<Card.Header>
{/* This was Accordion.Toggle in old version */}
<Accordion.Toggle as={Button} variant="link" eventKey={benefit.Id.toString()}>
{benefit.Name}
</Accordion.Toggle>
</Card.Header>
<Accordion.Collapse eventKey={benefit.Id.toString()}>
<Card.Body>
{benefit.Logo &&
<>
<img style={{width:"100%"}} src={"data: "+benefit.Logo.contentType+"; base64," + btoa(String.fromCharCode.apply(null, benefit.Logo.data)) }></img>
</>
}
<section
className="not-found-controller"
dangerouslySetInnerHTML={{ __html: benefit.Detail }}
/>
</Card.Body>
</Accordion.Collapse>
</Card>
</Accordion>
)
}
</div>
</>
}
</div>
</Col>
</Row>
</Container>
</div>
)
}
export default Index
Error Screen
Error Text:
RangeError: Maximum call stack size exceeded
(anonymous function)
C:/Source/Repos/Federation.Homestead/MyFfbfPortal/my-ffbf-portal/src/pages/benefits/Index.tsx:233
230 |
231 | {benefit.Logo &&
232 | <>
> 233 | <img style={{width:"100%"}} src={"data: "+benefit.Logo.contentType+"; base64," + btoa(String.fromCharCode.apply(null, benefit.Logo.data)) }></img>
| ^ 234 | </>
235 | }
236 | <section
Index
C:/Source/Repos/Federation.Homestead/MyFfbfPortal/my-ffbf-portal/src/pages/benefits/Index.tsx:175
172 |
173 | {
174 | categories.filter(category=>{return category.ParentId == categories[selectedParentCategoryIndex].id}).map(category=>
> 175 | <Accordion key={category.id+"sub"}>
| ^ 176 | <Card>
177 | <Card.Header>
178 | {/* This was Accordion.Toggle in old version */}
▶ 18 stack frames were collapsed.
LoadParent
C:/Source/Repos/Federation.Homestead/MyFfbfPortal/my-ffbf-portal/src/pages/benefits/Index.tsx:48
45 | const LoadParent = async (parentCategoryId:string) =>{
46 | var [_getMemberBenefits, _error] = await MyFfbfClientApi.Benefits.GetMemberBenefits(parentCategoryId ?? 0);
47 | set_loadedMemberBenefits(_getMemberBenefits)
> 48 | set_selectedParentCategoryIndex(categories.findIndex(category=> category.id == parentCategoryId))
| ^ 49 | }
50 |
51 | // maybe fold these into 1 redirection checker function?
I think the problem is this: String.fromCharCode.apply it gets invoked for each byte/number in benefit.Logo.data inline and at a certain size the call stack exceeds.
The apply() method calls the specified function with a given this
value.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
But beware: by using apply this way, you run the risk of exceeding the
JavaScript engine's argument length limit. The consequences of
applying a function with too many arguments (that is, more than tens
of thousands of arguments) varies across engines. (The JavaScriptCore
engine has hard-coded argument limit of 65536.)
So internally it looks like this:
// `null` will be replaced with the global object
btoa(window.String.fromCharCode(benefit.Logo.data[0]) + window.String.fromCharCode(benefit.Logo.data[1]) + ...)
Maybe you can store the image as raw binary, like in Image() or ArrayBuffer() or similiar and call toString("base64") on that?
Pseudo code:
export interface ImageFile{
data: ArrayBuffer;
contentType: string;
fileName: string;
}
<img style={{width:"100%"}} src={"data: "+benefit.Logo.contentType+"; base64," + benefit.Logo.data.toString("base64") }>
References:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
https://developer.mozilla.org/en-US/docs/Web/API/Blob
https://developer.mozilla.org/en-US/docs/Glossary/Base64
I wanted to know what I'm doing wrong, to extract the first category from the Wordpress api.
I have a list of posts, and I just need to show the category, no link or anything.
With the code below it is bringing me an empty value.
export default function Blog({ posts }) {
const { status } = useSession();
if (status === 'loading') return <Loading />;
const getCategories = async (id) => {
const response = await axios.get(`${process.env.API_CONTENT}/categories/${id}`);
const category = response.data;
return category;
};
return (
<BlogPosts>
<Container className="default">
{posts.map((post, i) => (
<Post key={i}>
<Row>
<Col className="post-image" md={6}>
<PostImage>
<Link href={`/blog/${post.id}`}>
<a title={post.title.rendered}>
<img className="image" src={post._embedded['wp:featuredmedia']['0'].source_url} />
</a>
</Link>
</PostImage>
</Col>
<Col className="post-container" md={6}>
<PostContent>
<Link href={`/blog/${post.id}`}>
<a title={post.title.rendered}>
<h2 className="title">{post.title.rendered}</h2>
</a>
</Link>
<PostDetails date={post.modified} category={getCategories(post.categories[0])} />
<div className="excerpt" dangerouslySetInnerHTML={{ __html: post.excerpt.rendered }} />
<Link href={`/blog/${post.id}`}>
<a className="link" title={post.title.rendered}>
LEIA MAIS +
</a>
</Link>
</PostContent>
</Col>
</Row>
</Post>
))}
</Container>
</BlogPosts>
);
}
Good evening, have a question. I am starting to use react making a project with sponacular api. I have this code:
import Container from 'react-bootstrap/Container';
import Button from 'react-bootstrap/Button';
import Card from 'react-bootstrap/Card';
import Row from 'react-bootstrap/Row';
import ListGroup from 'react-bootstrap/ListGroup';
import { useContext } from 'react';
import { CartContext } from '../../CartContex/CartContext';
import "./CartOrden.css";
const CartOrden =()=>{
const {pedidoVegano, pedidoNoVegano, removeItem } = useContext(CartContext);
let totalPrecio = 0;
let tiempoEspera = 0;
let healthScore = 0;
const sumarTotal =(i)=>{
totalPrecio += i.pricePerServing;
console.log(totalPrecio)
}
const calculoEspera =(i)=>{
tiempoEspera += parseInt(i.readyInMinutes);
console.log(tiempoEspera)
}
const totalHealth = (i)=>{
healthScore += i.healthScore;
console.log(healthScore)
}
return (
<Container>
<div>
<h2>Vegan Menu</h2>
</div>
<Row className='m-3'>
{pedidoVegano.map((i=>{
sumarTotal(i.item)
calculoEspera(i.item)
totalHealth(i.item)
return(
<Card className='card-first' style={{ width: '18rem' }}>
<Card.Img className='card-img' variant="top" src={i.item.image} />
<Card.Body>
<Card.Title className='card-title'>{i.item.title}</Card.Title>
<div className='contain-value'>
<p className='text'><i className="fa-solid fa-dollar-sign"></i> {i.item.pricePerServing}</p>
<p className='text'><i className="fa-solid fa-heart"></i> {i.item.healthScore}</p>
<p className='text'><i class="fa-solid fa-clock"></i> {i.item.readyInMinutes}</p>
</div>
<div>
<Button onClick={()=> removeItem(i.item)} variant="danger"><i class="fa-solid fa-trash"></i> Delete</Button>
</div>
</Card.Body>
</Card>
)
}))}
</Row>
<div>
<h2>Vegan't Menu</h2>
</div>
<Row className='m-3'>
{pedidoNoVegano.map((i=>{
sumarTotal(i.item)
calculoEspera(i.item)
totalHealth(i.item)
return(
<Card className='card-first' style={{ width: '18rem' }}>
<Card.Img className='card-img' variant="top" src={i.item.image} />
<Card.Body>
<Card.Title>{i.item.title}</Card.Title>
<div className='contain-value'>
<p className='text'><i className="fa-solid fa-dollar-sign"></i> {i.item.pricePerServing}</p>
<p className='text'><i className="fa-solid fa-heart"></i> {i.item.healthScore}</p>
<p className='text'><i class="fa-solid fa-clock"></i> {i.item.readyInMinutes}</p>
</div>
<div>
<Button onClick={()=> removeItem(i.item)} variant="danger"><i class="fa-solid fa-trash"></i> Delete</Button>
</div>
</Card.Body>
</Card>
)
}))}
</Row>
<Row className='m-3'>
<Card>
<Card.Header as="h5">Current Menu</Card.Header>
<Card.Body>
<Card.Title>Total price: {totalPrecio}</Card.Title>
<Card.Title>Total health score: {healthScore} </Card.Title>
<Card.Title>Total preparation time: {tiempoEspera} minutes </Card.Title>
</Card.Body>
</Card>
</Row>
</Container>
)
}
export default CartOrden;
I wanted to unstructure the previous code, to make it more complex and work with components, as it should.
import Button from 'react-bootstrap/Button';
import Card from 'react-bootstrap/Card';
import { useContext } from 'react';
import { CartContext } from '../../CartContex/CartContext';
import "./CartOrden.css";
const CartOrden =({i})=>{
const { removeItem } = useContext(CartContext);
return(
<Card className='card-first' style={{ width: '18rem' }}>
<Card.Img className='card-img' variant="top" src={i.item.image} />
<Card.Body>
<Card.Title className='card-title'>{i.item.title}</Card.Title>
<div className='contain-value'>
<p className='text'><i className="fa-solid fa-dollar-sign"></i> {i.item.pricePerServing}</p>
<p className='text'><i className="fa-solid fa-heart"></i> {i.item.healthScore}</p>
<p className='text'><i class="fa-solid fa-clock"></i> {i.item.readyInMinutes}</p>
</div>
<div>
<Button onClick={()=> removeItem(i.item)} variant="danger"><i class="fa-solid fa-trash"></i> Delete</Button>
</div>
</Card.Body>
</Card>
)
}
export default CartOrden;
import Container from 'react-bootstrap/Container';
import Card from 'react-bootstrap/Card';
import Row from 'react-bootstrap/Row';
import { useContext } from 'react';
import { CartContext } from '../../CartContex/CartContext';
import CartOrden from '../CartOrden/CartOrden';
const ResultOrden =()=>{
const {pedidoVegano, pedidoNoVegano, } = useContext(CartContext);
let totalPrecio = 0;
let tiempoEspera = 0;
let healthScore = 0;
const sumarTotal =(i)=>{
totalPrecio += i.pricePerServing;
console.log(totalPrecio)
}
const calculoEspera =(i)=>{
tiempoEspera += parseInt(i.readyInMinutes);
console.log(tiempoEspera)
}
const totalHealth = (i)=>{
healthScore += i.healthScore;
console.log(healthScore)
}
return (
<Container>
<div>
<h2>Vegan Menu</h2>
</div>
<Row className='m-3'>
{pedidoVegano.map((i=>{
sumarTotal(i)
calculoEspera(i)
totalHealth(i)
return(
<CartOrden i={i} key={i.pricePerServing}/>
)
}))}
</Row>
<div>
<h2>Vegan't Menu</h2>
</div>
<Row className='m-3'>
{pedidoNoVegano.map((i=>{
sumarTotal(i)
calculoEspera(i)
totalHealth(i)
return(
<CartOrden i={i} key={i.id}/>
)
}))}
</Row>
<Row className='m-3'>
<Card>
<Card.Header as="h5">Current Menu</Card.Header>
<Card.Body>
<Card.Title>Total price: {totalPrecio}</Card.Title>
<Card.Title>Total health score: {healthScore} </Card.Title>
<Card.Title>Total preparation time: {tiempoEspera} minutes </Card.Title>
</Card.Body>
</Card>
</Row>
</Container>
)
}
export default ResultOrden;
I wanted to know why in the first case the code works but in the second within ResultOrden, the healthScore, tiempoEspera and totalPrice returns NaN.
example image
Sorry if the question is basic, I was trying to solve it and I couldn't. I'm probably missing something about communication between components but couldn't find it. If anyone can give me some advice, I'd appreciate it.
the initialState/loggedState methods seem to not be working... nothing will return
Can anyone point out what I did wrong? I'm stomped literally about to call it a day
...
Also useState works (kinda) but whenever I update the page it reverts back to initialState
ps. StackOverflow should let us post no matter how much code we have
import React, {useEffect} from 'react'
import './Home.css'
import {Card, Figure} from 'react-bootstrap'
import Data from './Data'
import {useMoralis} from 'react-moralis'
function Today() {
const { user } = useMoralis();
const initialState = (
<div className='status'>
<p>Guest</p>
</div>
)
const loggedState = (
<div className='status'>
<p>#</p>
</div>
)
const value = useEffect(() => {
if (user ) {
return(loggedState)
} else {
return(initialState)
}})
const current = new Date();
const date = `${current.getDate()}/${current.getMonth()+1}/${current.getFullYear()}`;
return(
<div>
<div className='top'>
<Card style={{ width: '100%' }} >
<Card.Body>
<Card.Title><span className='card-titled'>Home</span></Card.Title>
<Card.Subtitle className="mb-2 text-muted">Dashboard</Card.Subtitle>
<Card.Text>
Date: {date}
</Card.Text>
</Card.Body>
<Card.Body className='bannerlogo'>
<img src='https://upload.wikimedia.org/wikipedia/commons/thumb/0/05/Ethereum_logo_2014.svg/73px-Ethereum_logo_2014.svg.png' alt="Girl in a jacket" width="60" height="90" />
</Card.Body>
<Card.Body className='profilepic'>
<Figure>
<Figure.Image
width={60}
height={70}
alt="171x180"
src="https://3.bp.blogspot.com/-UI5bnoLTRAE/VuU18_s6bRI/AAAAAAAADGA/uafLtb4ICCEK8iO3NOh1C_Clh86GajUkw/s320/guest.png"
/>
<Figure.Caption>
{value}
</Figure.Caption>
</Figure>
</Card.Body>
</Card>
</div>
<Data/>
</div>
)
}
export default Today
No need to use useEffect. you have useMolaris is custom hook already
function Today() {
const { user } = useMoralis();
const InitialState = (
<div className='status'>
<p>Guest</p>
</div>
)
const LoggedState = (
<div className='status'>
<p>#</p>
</div>
)
const current = new Date();
const date = `${current.getDate()}/${current.getMonth()+1}/${current.getFullYear()}`;
//Put conditional rendering if there's no user in functional component
if(!user) return <InitialState />
return(
<div>
<div className='top'>
<Card style={{ width: '100%' }} >
<Card.Body>
<Card.Title><span className='card-titled'>Home</span></Card.Title>
<Card.Subtitle className="mb-2 text-muted">Dashboard</Card.Subtitle>
<Card.Text>
Date: {date}
</Card.Text>
</Card.Body>
<Card.Body className='bannerlogo'>
<img src='https://upload.wikimedia.org/wikipedia/commons/thumb/0/05/Ethereum_logo_2014.svg/73px-Ethereum_logo_2014.svg.png' alt="Girl in a jacket" width="60" height="90" />
</Card.Body>
<Card.Body className='profilepic'>
<Figure>
<Figure.Image
width={60}
height={70}
alt="171x180"
src="https://3.bp.blogspot.com/-UI5bnoLTRAE/VuU18_s6bRI/AAAAAAAADGA/uafLtb4ICCEK8iO3NOh1C_Clh86GajUkw/s320/guest.png"
/>
<Figure.Caption>
{value}
</Figure.Caption>
</Figure>
</Card.Body>
</Card>
</div>
<Data/>
</div>
)
}
export default Today
Reactjs shows this error when i open modal that is from another component
"index.js:1 Warning: findDOMNode is deprecated in StrictMode. findDOMNode was passed an instance of Modal which is inside StrictMode. Instead, add a ref directly to the element you want to reference."
I've tried alot of other solutions but none of them work in my case
my code file:
class Routes extends Component {
componentDidMount() {
console.log('Component did mount!')
}
loginModalRef = ({ handleShow }) => {
this.showModal = handleShow;
}
onLoginClick = () => {
this.showModal();
}
ShopersModalRef = ({ handleShoperShow }) => {
this.showShoperModal = handleShoperShow;
}
onShopersClick = () => {
this.showShoperModal();
}
//ChargeModalRef = ({ handleChargeShow }) => {
// this.showChargeModal = handleChargeShow;
//}
// onChargeClick = () => {
// this.showChargeModal();
// }
render() {
return (
<div>
{/*<chargeFeeModal ref={this.ChargeModalRef}></chargeFeeModal>*/}
<FormModal ref={this.loginModalRef}></FormModal>
<ShopersModal ref={this.ShopersModalRef}></ShopersModal>
<AppBar position="sticky" className="appbar">
<Toolbar className="NavbarTop">
<div className='row w-100'>
<div className="col-4 LogoOrBack">
<section className="leftBox shopname ml-4">
<Typography className="typography">
{Text}
</Typography>
</section>
</div>
<div className="col-4 centered">
<section className="centerBox">
<Typography className="typography">
<b>Stores</b>
</Typography>
</section>
</div>
<div className="col-4 righted">
<section className="rightBox">
<Typography className="typography">
<Button className="primary btn AccountBtn" onClick={this.onLoginClick}>
<img alt="user account avatar" src={require('../../../assets/images/placeholder_account.png')} className="buttonImage" /> Account
</Button>
<Button className="primary btn" onClick={this.onLoginClick}>
<i className="fa fa-cart-plus cart"></i>
</Button>
</Typography>
</section>
</div>
</div>
</Toolbar>
<Toolbar>
<div className='row w-100'>
<div className='col-lg-4'>
{(() => {
//Javascript for changing buttons
switch (history.location.pathname) {
case "/": return <Button onClick={this.onLoginClick} className="primary postalCodeBtn" >
<img alt="home icon" src={require('../../../assets/images/homeicon.png')} className="buttonImage" /> <b>M4b 146, CA</b> <i className="fa fa-chevron-down downIco"></i>
</Button>;
default: return (
<Button onClick={this.onShopersClick} className="primary postalCodeBtn" >
<img alt="home icon" src={require('../../../assets/images/time.png')} className="buttonImage" /> <b style={{ textTransform: 'capitalize' }}>Shoppers Occupied</b>
</Button>
);
}
})()}
</div>
<div className="col-lg-4 centered p-1 pl-4" >
<div className="searchContainer">
<i className="fa fa-search searchIcon"></i>
<input className="searchBox" type="search" name="search" placeholder="Search Stores" />
</div>
</div>
{TabsShowOrNo}
</div>
</Toolbar>
</AppBar>
<AnimatedSwitch
atEnter={{ opacity: 0 }}
atLeave={{ opacity: 0 }}
atActive={{ opacity: 1 }}
className="switch-wrapper"
>
<Route exact path="/" component={HomePage} />
<Route path='/store/orders/' component={OrdersPage} />
<Route path='/store/aisles/' component={AislesPage} />
<Route path="/store/featured" component={SingleStorePage} />
<Route component={NotFound} />
</AnimatedSwitch>
</div >
)
}
}```
any help will be appreciate