Home > Enterprise >  useState keeps initial state after defining it in useEffect
useState keeps initial state after defining it in useEffect

Time:12-16

I have an async function that fetches some data from an API. Since I need that data to properly load my component I decided to fetch the data in the useEffect and then store it in a useState what works just fine. However, if I try to console log it, it just shows its initial state what technically would mean it's still unset or that the console log runs before assigning the useState.

Thanks for your help in advance.

const [categories, setCategories] = useState([])

useEffect(() => {
    fetchListProductCats().then(function(result){
        setCategories(result.data)
    })
    console.log(categories) // returns -> []
    
}, []);

if(!categories.length){
    return "loading"
}

CodePudding user response:

async function with Promise, make sure you know what it means.

The console.log line in this code always runs before the Promise resolved.

If you want to observe the changing of categories, use another useEffect:

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

CodePudding user response:

Your state is already updated with data you wanted its showing categories with it's initial values because you have rendered useEffect with no dependancies. And it is consoled befored being updated. Try using below code snippets to log.

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

CodePudding user response:

React setState is async. It won't update immediately after calling the function. It will go through a re-rendering process first to update the user interface. Once re-rendering is done, the functions provided in the useEffect hook will be called.

useEffect(()=>{
  console.log(categories)
}, [categories]) 
  • Related