Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

159
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda