Home > Back-end >  React Native setState doesn't effect immediately data
React Native setState doesn't effect immediately data

Time:08-30

I am developing a project with react native.After using axios fetch data , then I changed my billingList state using returning data,but after that when I want logged this state,my array is blank.Data is returning but state doesn't change immediately.

 axios.get(url, config)
            .then(function (response) {
                if (response.data.status === true) {
                    console.log(response.data.data);
                    setBillingList(response.data.data)           
                    console.log(billingList);

                }
            })
            .catch(function (error) {
                console.log(error);
            })
       
    }

So using this data in responsive table,table is blank .

import { TableView } from "react-native-responsive-table"


 return (


        <View>
            <TableView
                headers={[
                    {
                        name: "S.no.",
                        reference_key: "no",
                    },
                    {
                        name: "Name",
                        reference_key: "name",
                    },
                    {
                        name: "Age",
                        reference_key: "age",
                    },
                ]}
                rows={billingList}
            />
        </View>
      

    )

CodePudding user response:

The reason is that state update does not happen immediately. This is because when we call the setState function, the entire component gets re-rendered – so React needs to check what all needs to be changed using the Virtual DOM algorithm and then perform various checks for an efficient update of the UI.

This is the reason you may not get the updated value instantly.

CodePudding user response:

Try putting your axios request in useEffect:

useEffect(() => {
    axios.get(url, config)
        .then(function (response) {
            if (response.data.status === true) {
                console.log(response.data.data);
                setBillingList(response.data.data)           
                console.log(billingList);

            }
        })
        .catch(function (error) {
            console.log(error);
        })
   
}
}, [])

I have done this multiple times and it should work!

  • Related