Search code examples
reactjsreact-hooksfetchuse-effect

React fetch data and set state accordingly doesn't work


In the code below the settings variable is not being set. I did check with console.log after the setSettings and also I verified the component using the variable is receiving the default {} value. The fetch per se is right, I tried in the browser's console and I see the json in the Network tab.

I need the fetch be done once, at the first rendering.

Could you please take a look? I've spent lots of time on this and I'd like to know what I'm doing wrong. Thanks!

    const [settings, setSettings] = React.useState({});

    function fetchSettings() {
        fetch("MYAPIENDPOINT/settings", {
            method: "GET",
            credentials: 'include',
            accept: 'application/json',
        })
        .then(response => {
            if (response.ok) {
                return response.json();
            }
            throw response;
        })
        .then((data) => {
            setSettings(data);
        })
        .catch(error => {console.log(error);});

    }

    React.useEffect(
        fetchSettings(),
        [settings]
    );

EDIT to show the component using the settings variable

    ...
    <div id="Grid" style={{ height: "700px" }}>
        {settings && <GenericGrid settings={settings} />}
    </div>

Solution

  • useEffect accepts 2 arguments: callback and dependency array.

    The right syntax is:

    useEffect(() => {
       function fetchSettings(){
          ...
       }
    
       fetchSettings();
    }, []) 
    

    If you want the callback to trigger only once, leave the dependency array empty. Also better define the fetchSettings function inside the callback, so it does not recreate on each render.