I am trying to get info from an api but the useState() doesn't work correctly. I have a work order grid by double click on each row I get the work order id then I should get the information from a specific api route to "workorder/:id" and display them. but when I try to console log the information by double click on a row I get "undefined"
here is my code:
const gridOptions = {
onRowDoubleClicked: openWorkOrder,
}
function openWorkOrder(row) {
const workOrderId = row.data.id
navigate(`workorder/${workOrderId}`)
fetch(`baseURL/api/Gages/WorkFlow/GetProductDetailByOrderId?id=${workOrderId}`)
.then((result) => result.json())
.then((data) => props.setDetails(data))
console.log(props.details)
}
const [details, setDetails] = useState()
is defined in the parent component.
CodePudding user response:
The function returned by useState
does not update the state immediately. Instead, it tells React to queue a state update, and this will be done once all event handlers have run.
Once the component is re-rendered, you will then see the new state.
When you console.log
right after the fetch, the component has not yet re-rendered, and hence you see undefined
.
CodePudding user response:
Fetch is async
, and you placed console.log()
after it, so there are no props.details
at this moment. You can try to convert openWorkOrder
to async
function and await
for fetched results.
CodePudding user response:
The useState
in React is an asynchronous hook.
When you call useState, it doesn't update state immediately.
If you want to get updated state, you must use useEffect
hook.
import { useEffect } from "react";
useEffect(() => {
console.log(details)
},[details]);
For more Detail about React useEffect hook refer to documentation
Also Refer to Is setState() method async? and Change is not reflected and await useState in React for more detail