Search code examples
javascriptreactjshttp-postuse-effect

React useEffect caused infinite loop


I searched lots of post about infinite loop when using useEffect, but still can't figure it out

Inside the useEffect, I was trying to call get accounts api, and of course, I put an empty array because I only want it run once after render. But currently I like to add 'addAccount' function. So, if I press the add button, then it sends a post request. Here is the question, I would like to check if the value has changed or not, so I put the value into the second parameter which is the empty array, and it causes infinite loop. However, if I keep the empty array, my screen does not re-render.

export default function BC() {
  const [value, setValue] = useState([])

  async function getBCAccount() {
    const result = await axios.get("http://localhost:3004/accounts")
    if(result) {
      setValue(result.data)
    }
  }
  
  async function createBCAccount() {
    const result = await axios.post("http://localhost:3004/accounts", {
      id: 5,
      name: "mmm"
    })
  }
  
  useEffect(()=> {
    getBCAccount()
  }, [])

  const handleAddAccount = () => {
    createBCAccount()
  }

  return (
    <BcContainer>
      <button onClick={handleAddAccount}>add</button>
      {value && value.map((v)=> (
        <AccountContainer key={v.id} to={`/bc/${v.id}`}>
          <p>{v.name}</p>
          <p>{v.coin} BTC</p>
        </AccountContainer>
      ))}
    </BcContainer>
  )

Solution

  • I think you just call getBCAccount inside createBCAccount. After create, you will call get data again to update your value:

      async function createBCAccount() {
        await axios.post("http://localhost:3004/accounts", {
          id: 5,
          name: "mmm"
        })
        getBCAccount()
      }