简体   繁体   中英

React Hook setting state in useEffect with state in dependency array

I have a question about the correct usage with useEffect and setState in React Hooks.

here is my react app that gets a persisted configuration and some other data depending on the config like this:

function App() {
    const [config, setConfig] = useState(null);
    // some other states 

    useEffect(() => {
        const fetchData = () => {
            axios.get("/path/to/config").then(response => {
                if (response.status === 200) {
                    return response.data
                }
            })
                .then(data => {
                    setConfig(data.config);
                    // set some other states
                })
                .catch(error => {
                    console.log("Error:" + error);
                })
        }
        fetchData();
    }, [config]);

    return (
        <div >
            ...
        </div>
    );
}

If I run this App useEffect is instantly called twice one time for first render and then a second time because setConfig(data.config); is called in the axios get success function.

The user has the possibility to change his own config that is done in another request. If he does I want after state config changes that the config and some other data depending on the config is reloaded via this useEffect function.

Now since there is no setstate callback in react hooks I read somewhere I should use useEffect with the state variable in the dependency array.

How can I prevent that my useEffect is called twice right at the beginning?

I have the feeling that I am doing it all wrong. Thank you in advance

You need to add an if condition in useEffect, because useEffect is called by default on first render.

useEffect(() => {
      if(config !== null){
        const fetchData = () => {
            axios.get("/path/to/config").then(response => {
                if (response.status === 200) {
                    return response.data
                }
            })
                .then(data => {
                    setConfig(data.config);
                    // set some other states
                })
                .catch(error => {
                    console.log("Error:" + error);
                })
        }
        fetchData();
      }
    }, [config]);

This is not right. I guess this can call fetchData infinitely.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM