简体   繁体   中英

Setting Axios Response as State. Error: Too many re-renders. React limits the number of renders to prevent an infinite loop

I'm trying to build a Component that

  1. Uploads a File to an API using Axios.
  2. The Response is Stored and passed on to another Component.

But using the Below code I'm getting the errors of Too Many re-renders and the Error Highlights

setData({ completeData: res.data })

The Entire Code for the Component is Given Below. I'm relatively new to React and have been trying to find the root cause of this error for more than 3 days, but no help. I can't get where am I going wrong.

const UploadChat = () => {
  const [data, setData] = useState({
    selectedFile: "Hi",
    completeData: null,
  })


  const fileUpload = (e) => {
    e.preventDefault()
    let file = e.target.files[0]
    setData({
      selectedFile: file,
    })
  }

  const submitChat = async (e) => {
    e.preventDefault()
    let postData = new FormData()
    postData.append("file", data.selectedFile)
    try {
      const res = await axios.post("http://127.0.0.1:4555/upload", postData)
      setData({ completeData: res.data })
    } catch (err) {
      console.log(err)
    }
  }

  return (
    <div>
      <form onSubmit={(e) => submitChat(e)}>
        <input type="file" name="myfile" onChange={(e) => fileUpload(e)} />
        <input type="submit" name="submit" />
      </form>
      {data.completeData ? (
        <Redirect to={{ pathname: "/dashboard", state: data.completeData }} />
      ) : (
        <h1>Not</h1>
      )}
    </div>
  )
}

Without thinking too much about it, does it work with

setData((prevData) => ({ ...prevData, completeData: res.data }))

?

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