Search code examples
javascriptreactjsuse-effectuse-state

useState keeps initial state after defining it in useEffect


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"
}

Solution

  • 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]);