Home > Enterprise >  ReactJS Infinite request loop when using useState
ReactJS Infinite request loop when using useState

Time:11-18

I'm starting out my path with front end and I'm encountering some issues when trying to integrate my front end with my backend API.

I know I need to use states but some issues are arising when trying that out, mainly an infinite loop of requests happening.

Here's a snippet of what I'm doing

const AppLayout = () => {
    const [
        loading, 
        setLoading
    ] = useState(true);

    const [
        userState, 
        setUserState
    ] = useState(null);

    const populateUser = async() =>{
        let profile_data = await UserService.findUser()
        const user = {"name": profile_data["name"]}

        setUserState(user)
        setLoading(false)
    }

    populateUser()

    return(
        <>
        {
            !loading && <h1>{userState.name}</h1>
        }
        </>
    )
}

Is this the correct way of doing this? By executing this, I'm getting stuck in a loop of requests to the API.

Edit1: I was not clear in my objective here. The idea for this is simply to show the name of the user. This is being obtained via the UserService which interacts with the API.

CodePudding user response:

You should use a useEffect hook to handle the async call.

const AppLayout = () => {
    const [
        loading, 
        setLoading
    ] = useState(true);

    const [
        userState, 
        setUserState
    ] = useState(null);

    const populateUser = async() =>{
        let profile_data = await UserService.findUser()
        const user = {"name": profile_data["name"]}

        setUserState(user)
        setLoading(false)
    }

    useEffect(async () => {
        await populateUser()
        return () => { ignore: true }
    }, [])
    

    return(
        <>
        {
            !loading && <h1>{userState.name}</h1>
        }
        </>
    )
}

This will populate on render of the component. Since you are using functional components you should read about hooks, here is a good reading.

  • Related