0

I have the function handleClick that sets my workout state variable and the useEffect that performs a post request to create a document with Mongoose. My question is: upon creating the document, mongoDB gives it an _id property; how can my workout state variable have access to that property? If I try to use setWorkout to set it, it results in an infinite loop since setWorkout would call useEffect again.

  useEffect(() => {
    async function postWorkout() {
      const res = await axios.post('/workouts', workout)
      const id = res.data._id
      setWorkout(prev => ({
        ...prev,
        _id: id
      })
    }
    try {
      postWorkout()
    } catch(error) {
      throw error
    }
  }, [workout])

  const handleClick = () => {
    setWorkout({
      mains: mains,
      accessories: accessories
    })
  }
nalanart
  • 41
  • 6
  • You use badly the post operation. Why do you make the post on the useEffect instead calling it directly in the method handleClick ? – Hamza Khattabi Nov 17 '20 at 22:38
  • Because setting a state is asynchronous. The changes will not have taken place until the next render so if I make the post request right after, it will not have the values I have just set. – nalanart Nov 17 '20 at 22:43
  • You can make your method handleClick asynchronous. retrieve data from your api and set you state with the new data. It will be updated after setting the state – Hamza Khattabi Nov 17 '20 at 22:52
  • I want to set my data first and then make the post request though. See the link for my previous question: https://stackoverflow.com/questions/64883012/how-to-make-post-request-with-axios-and-react-state-hook/64883112#64883112 – nalanart Nov 17 '20 at 22:58

0 Answers0