Home > Enterprise >  useState does not get updated value
useState does not get updated value

Time:08-02

I am working with a list with useState, so I select an element from the list and update the selected record in the database and retrieve the updated list but when going through the list to obtain the updated value(1), the list does not have the updated values as they are shown in the view, how can I get the list with the updated values?

const location = useLocation();
const credito = location.state;
const [lstCuotas, setLstCuotas]  = useState([]);
const [cuota, setCuota] = useState({
    id : '',
    numero: '',
    monto: '',
    montoPago: '',
    simboloMoneda: '',
    moneda: '',
    fecha: '',
    fechaPago: '',
    idEstado: '',
    idCredito: '',
    estado: '',
    lstPago: []
});

const fetchCuotas = useCallback (async () => {
    const response = await fetch(SERVER_URL 'api/credito/listcuotas/' credito.id);
    const responseData = await response.json();
    const loadedCuotas = [];
    for (const key in responseData) {
        loadedCuotas.push({
            id: responseData[key].id,
            numero: responseData[key].numero,
            monto: responseData[key].monto,
            montoPago : responseData[key].monto,
            simboloMoneda: credito.simboloMoneda,
            moneda: credito.moneda,
            fecha: responseData[key].fecha,
            fechaPago : '',
            idEstado: responseData[key].idEstado,
            idCredito: responseData[key].idCredito,
            estado: responseData[key].estado,
            lstPago: responseData[key].pagos
        });
    }
    setLstCuotas(loadedCuotas);
},[credito]);

useEffect(() => {
  fetchCuotas();
}, [fetchCuotas]);

const handlePagoCuota = (event) => {
    onCreatePagoCuota(event);
};

const onCreatePagoCuota = async(event) => {
    event.preventDefault();
    await fetch(SERVER_URL   'api/credito/pagocuota', {
        method: 'POST',
        headers: { 
            'Content-Type':'application/json'
        },
        body: JSON.stringify(cuota)
    })
    .then(response => {
        if (response.ok) {
            fetchCuotas();//(1)
            const cuotaTemp = lstCuotas.find(c => c.id === cuota.id);
            setCuota(cuotaTemp);
            if(cuotaTemp.estado === 'CANCELED') {
                console.log('CUOTA IS CANCELED');
            }
        }
        else {
            alert('Something went wrong!');
        }
    })
    .catch(err => console.error(err))
};

thanks for all.

CodePudding user response:

You're using lstCuotas from the same render cycle, which means the value inside your callback function is the original value, not the updated value set by fetchCuotas. This behaviour is intentional.

if (response.ok) {
  fetchCuotas();

  // lstCuotas is the _original_ value at the time the component rendered,
  // **NOT** the updated value from `fetchCuotas`.
  const cuotaTemp = lstCuotas.find(c => c.id === cuota.id);

  // ...
}

The easiest fix would be to return the updated list from your fetchCuotas function:

const fetchCuotas = useCallback (async () => {
    const response = await fetch(SERVER_URL 'api/credito/listcuotas/' credito.id);
    const responseData = await response.json();
    const loadedCuotas = [];

    for (const key in responseData) {
        loadedCuotas.push({ /* ... */ });
    }

    setLstCuotas(loadedCuotas);
    return loadedCuotas;
}, [credito]);

And now use the returned value in your callback - note that fetchCuotas is async so you have to await the result:

if (response.ok) {
  const updatedCuotas = await fetchCuotas();
  const cuotaTemp = updatedCuotas.find(c => c.id === cuota.id);

  // ...
}
  • Related