Home > Software engineering >  React hooks setState value is undefined in first time after component was rendered
React hooks setState value is undefined in first time after component was rendered

Time:06-27

I have an array of stuff that gets pulled from an api, I need to set result of that async call to my state "ordersState" and use that state value as a parameter for another component "ChartBuilder".

The issue here is that when my component "Orders" was rendered the state value at the beginning is still undefined. After I did logging I can see that the first two calls are undefined and only after that the state has value.

How to avoid this behavior ? without using timeout ?

export default function Orders() {
    const [ordersState, setOrdersState] = useState();

    const getOrders = useCallback(async () => {
        setOrdersState(await foo());
      }, []);
    
      useEffect(() => {
        getOrders()
      }, [getOrders])


    console.log('ordersState ', ordersState);

    return (
        <Grid item xs={12} md={12} lg={10} sx={{ mt: 3 }}>
            <Stack spacing={3}>
                <ChartBuilder
                    title="Orders"
                    chartLabels={["Jan", "Feb", "Apr."]]}
                    chartData={[
                        { name: 'orders', data: ordersState },
                    ]}
                />
            </Stack>
        </Grid>
    )
}

It looks like that child component "ChartBuilder" is not re-rendering after parent component state has been changed

CodePudding user response:

you have two options here: set ordersState to a default value usable like an empty array with

useState([])

otherwise you need to handle the undefined case. Kind of this:

if (!ordersState) return (<h1>No orders</h1>)
else  return (
        <Grid ...
  • Related