Search code examples
reactjsreact-hooksfetch-apiuse-effectusecallback

state update not happening in useEffect with api call


I'm new to React.js. I want to update options in my form based on some other state.I'm calling an api to fetch the new options. So this api needs to be called whenever state change happens.

const [selectedNamespace,setselectedNamespace] = useState[default];

whenever selectedNamespace changes, I need to call fetchData api.

 const fetchItemData = useCallback(() => {
        setError(null);
        setSuccessMessage(null);
        fetch(getApiPath + selectedNamespace)
            .then(response => {
                if (!response.ok) {
                    throw new Error('Something went wrong while fetching item data');
                }
                return response.json();
            }).then(data => {
                setItemData(data);
            }).catch(error => {
                setError(error.message);
            })
    }, []);

This is the useEffect function that I'm using to call this :

 useEffect(() => {
        if (!isEmptyString(selectedNamespace))
            fetchItemData();
    }, [selectedNamespace, fetchItemData])

The problem that I'm facing is that the selectedNamespace parameter that I'm accessing in my fetchItemdData is always empty. I think the state update is getting delayed because of which I'm not able to get the selectedNamespace. I'm new to useEffect and useCallback hook. Can someone pls let me know my mistake and the proper way to handle this?


Solution

  • I'm pretty sure, you don't need to wrap fetchItemdData inside useCallback.

    The problem that I'm facing is that the selectedNamespace parameter that I'm accessing in my fetchItemdData is always empty.

    const fetchItemData = useCallback(() => {
       ...
    , []); // <--- empty dependency. This is why selectedNamespace always empty