Maryadi Poipo
Maryadi Poipo

Reputation: 1478

Uninfinite async function execution in next js

I'm new to next js. And I have one user.js file inside of my pages directory in next.js. This is the source code:

// pages/user.js
 function user(props) {
      const [userList, setUserList] = useState([])
      const [roleList, setRoleList] = useState([])
    
      async function initialFetch() {
        const userList = await fetch('GET', GET_ALL_USERS)
        setUserList(userList)
    
        const roleList = await fetch('GET', GET_ALL_ROLES)
        setRoleList(roleList)
    
        console.log('userList in async')
        console.log(userList)
      }
      
    
      if (!props.userList.status) {
        initialFetch()
      } else {
        setUserList(props.userList)
        setRoleList(props.roleList)
      }
    
      console.log('userList outside')
      console.log(userList)
      
      return (
      <>
        <TableUserManagement users={userList} roles={roleList}/>
      </>
      )
 };
    
 user.getInitialProps = async (ctx) => {
      const userList = await fetch('GET', GET_ALL_USERS)
      const roleList = await fetch('GET', GET_ALL_ROLES)
      return {userList, roleList}
    }

The problem is that above async initialFetch() function is always called uninfinitively : enter image description here

So what am I doing wrong here? Thank you

Note: I have tried to use useEffect() but the looping still happening. This the code :

 useEffect(
    () => {
      if (!props.userList.status) {
        initialFetch()
      } else {
        setUserList(props.userList)
        setRoleList(props.roleList)
      }
      console.log('user list diliuar')
      console.log(userList)
    }
  )

Upvotes: 0

Views: 3656

Answers (1)

dongnhan
dongnhan

Reputation: 1768

This issue is not related to Next.js but React itself. This is the code that cause unfinite calls:

if (!props.userList.status) {
  initialFetch()
} else {
  setUserList(props.userList)
  setRoleList(props.roleList)
}

Since after setting any state, your component re-renders and that part of code keeps running again, and the fetch cause setting state again,... that loops forever.

You should move you data-fetching logic in side componentDidMount or useEffect. Remember to provide the dependency array of useEffect. In this case, you may only need to fetch data only once so you should provide the empty dependency array.

useEffect(() => {
  async function initialFetch() {
    const userList = await fetch('GET', GET_ALL_USERS)
    setUserList(userList)

    const roleList = await fetch('GET', GET_ALL_ROLES)
    setRoleList(roleList)
  }
  

  if (!props.userList.status) {
    initialFetch()
  } else {
    setUserList(props.userList)
    setRoleList(props.roleList)
  }
}, []);

P/s: you should name you React component in PascalCase (ex: User)

Upvotes: 2

Related Questions