import Card from '../UI/Card'
import CartItem from './CartItem'
import './Cart.css'
import { useEffect, useRef } from 'react'
const Cart = (props) => {
let filteredCourses;
let creditCount;
let initialValue = 0;
const isMounted = useRef(false);
useEffect(() => {
if (isMounted.current) {
console.log("never again")
} else {
console.log("do something first time only")
isMounted.current = true;
}
},[]);
if(props.testing.length >0){
filteredCourses = props.testing.filter((course) => {
return course['theme'] ==="Software Engineering"});
console.log("filtered",filteredCourses)
}
if(props.selection.length>0){
let sum = props.selection.reduce(
(previousValue, currentValue) => previousValue + currentValue.credits,
initialValue
)
creditCount = "Number of credits: " + sum
}
let cartContents = props.selection.map(course =>
<CartItem onRemove = {props.onRemove} title = {course.title} credits = {course.credits}/>)
return(
<Card className="cart">
<h2>Module Selection
</h2>
{cartContents}
{creditCount}
</Card>
)
}
export default Cart
With the following snippet I am looking to only run on first mount. Even though the dependency array is empty I believe this will be re run when the component is unmounted and remounted which I am looking to prevent. On first run through the ref will be false but thereafter it will always be true and so this block should never run again. However the else part of this block continues to render?
const isMounted = useRef(false);
useEffect(() => {
if (isMounted.current) {
console.log("never again")
} else {
console.log("do something first time only")
isMounted.current = true;
}
},[]);