Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

useState and initial value as array does not work

I'm trying to use react hooks in my project and I have a problem with useState when I use array as value.

As you can see in my code below, when I display zoneItems that it should be like items array I get an empty array all the time. Would you have an explanation why?

When I use an object instead of array it works

const ShippingCostZone = ({ zone, datas, selectedProducts, getProductById }) => {
    const items = datas.items.filter(item => item.zoneId === zone.id)
    console.log('========> items', items) // ---- SHOW the good values
    const [zoneItems, updateItems] = useState(items)
    console.log('========> zoneItems  ', zoneItems)   // ---- SHOW all the time []
.........

Thanks in advance

like image 463
Victor Avatar asked Oct 23 '25 22:10

Victor


2 Answers

Due to async nature of hooks, you assignment useState(items) could be executed after you read the content of zoneItems. But react provides an hook that will be fired every time component will be loaded, or as you prefer, every time zoneItems changes his value: I'm talking about useEffect hook.

So if you want to print the zoneItems content every time is updated, just write something like this:

useEffect(() => {
    console.log(zoneItems);
}, [zoneItems])

This is the way that react provides to manage async assignment of state.

like image 166
Giovanni Esposito Avatar answered Oct 25 '25 13:10

Giovanni Esposito


I think you should initialize the state first as an array first then update it, as follows:

const ShippingCostZone = ({ zone, datas, selectedProducts, getProductById }) => {
    const items = datas.items.filter(item => item.zoneId === zone.id)
    console.log('========> items', items)

    const [zoneItems, updateItems] = useState([])
    
    updateitems(items)

    console.log('========> zoneItems  ', zoneItems)
like image 44
Abdeen Avatar answered Oct 25 '25 11:10

Abdeen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!