Please anyone help me. Thanks in advance.
while working, I got stuck on a problem. My useEffect
is not getting called. I have changed dependencies several times, but in vain.
Here is my code:
import React, { useEffect } from 'react'
import { Card, Col, Image, ListGroup, Row } from 'react-bootstrap'
import { useDispatch, useSelector } from 'react-redux'
import { Link, useParams } from 'react-router-dom'
import Loader from '../components/Loader'
import Message from '../components/Message'
import { getOrderDetails } from '../redux/actions/orderActions'
function OrderPage() {
const { id } = useParams()
const dispatch = useDispatch()
const orderDetails = useSelector(state => state.orderDetails)
const { order, error, loading } = orderDetails
debugger
useEffect(() => {
if (!order || order._id !== Number(id)) {
dispatch(getOrderDetails(id))
}
}, [order, dispatch, id, orderDetails])
if (!loading && !error) {
order.itemsPrice = order.orderItems.reduce((acc, item) => acc + item.price * item.qty, 0).toFixed(2)
}
Here, my useEffect
is not triggering first, rather it goes to check inside if
condition and throwing error. It seems peculiar to me as I have put condition !loading
& !error
. It should not check inside if
until I get order
from redux store
.
Please someone help me. Thanks again.
useEffect will always run the first time after the first render and then the other time it will run if any of the dependencies get changed
So you would need to have the below code for useEffect
useEffect(() => {
if (!order) {
dispatch(getOrderDetails(id))
} else if ( order._id !== Number(id) ) {
dispatch(getOrderDetails(id))
}
}, [order, dispatch, id, orderDetails])
This will check if the order is not there then get the order, or if the order is there but the order id does match with the id we get from the URL then also fetch the order.