0

I am seeing very odd behavior that I can't seem to resolve. I have spent many hours to no avail.

Problem

  • The form's initial submit does not seem to send props to the canvas component. It isn't until I hit submit for a second time the props are available in the canvas component. Below you will find my submit function that is in the page that is supposed to send props.

  • I am thinking it might be some sort of async issue but I can't seem to resolve it.

Any help is greatly appreciated!

 const handleSubmit = async (event) => {
    event.preventDefault()

    const radioSelected = { refreshRate }
    console.log(radioSelected)
    const RefreshRateSelected = JSON.stringify(radioSelected, null, 4)
    // console.clear()
    // console.log(json)
    const beginDate = epoch(startDate)

    // ... submit to API or something
    const res = await fetch(
      `/api/tracks/timeseries/${beginDate}/${rightThisSecond}`
    )

    const datePicker = {
      startTime: beginDate,
      endTime: rightThisSecond,
    }

    const polData = await res.json()
    console.log(polData)
    if (radioSelected.refreshRate === undefined) {
      console.log('select a radio')
      return setCanvas(<h2>Make sure you select a refresh rate!</h2>)
    }
    if (polData.error) {
      return setCanvas(<h2>{polData.error}</h2>)
    } else {
      // console.log('inside else polData: ' + polData)
      polData.unshift(JSON.parse(RefreshRateSelected))
      polData.unshift(datePicker)
      setTrack(polData)
      setCanvas(<Canvas data={track} />)
      return
    }
  }
rf guy
  • 379
  • 10
  • 26
  • Does this answer your question? [Why is setState in reactjs Async instead of Sync?](https://stackoverflow.com/questions/36085726/why-is-setstate-in-reactjs-async-instead-of-sync) – iunfixit Sep 02 '21 at 15:21
  • 2
    a quick fix may be to conditionally render `Canvas` in your main component with `{track && }` and then in your code just `setTrack(polData)` without `setCanvas()` – Nico Sep 02 '21 at 15:32
  • The conditional rendering did the trick! Thanks Nico! – rf guy Sep 02 '21 at 16:58

0 Answers0