Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

160
Vistas
useEffect is not getting called

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.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda