2

I do not fully understand this.setState in reactjs with async functions, so I posted a question on SO,
https://stackoverflow.com/questions...

I have accepted the given answer as it makes sense. but in reality the solution does not work, can anyone shed some light on it?

Comments
  • 1
    What exactly doesn't work?
  • 0
    @11000100111000 well, this.setState should update the state of the form, in this case, I'm clearing the form if (form.status === 200), but it is not quite working. You'll find code and more details in link.
  • 1
    @nothappy H! Checkout this way:

    Set an initial state "status" as null. Then in the function that calls the API, after the axios promise, call setstate to change the status like

    const res = await axios.post()

    this.setState({ status: res.status })

    Then Keep the success div inside a function component like

    renderSuccess(){
    If(this.state.status === 200){
    // Success component
    return </div>
    }else if (this.state.status === 400){
    // Failed component
    return <Fail/>
    }else {
    Since the status is null from when the component mounts, render nothing, so this else statement should return null
    }
    }

    So you can now add this function in your main form page as
    {this.renderStatus()}

    - it doesn't render anything when the component mounts

    - after the request, it changes the status from null to the actual status

    - after changing, the component gets the state change and reacts to it. Then it either renders the fail or success component.

    Good luck!
  • 1
    Sorry if I made any typo. I typed it in a rush
  • 1
    @leksyib yes, for showing success message I did something like this and for clearing rest of the form fields I did a patchwork (IMO), like this
    getElementByID("formid").reset(); on (form.status === 200).
  • 1
    @nothappy You really shouldn't be doing that in react. You don't manipulate the dom directly like that. React uses a virtual dom so every manipulation you're doing should be react-based
  • 1
    @leksyib yeah I know, but this.setState isn't updating the state
  • 1
    @nothappy can I see the repo you're doing this? I can raise a PR so you'll get what I'm talking about
  • 0
    @leksyib private project, sorry 😓
  • 0
    @nothappy setState is not an immediate operation
  • 0
    @leksyib okay I'll share repo give you le gitlab username
  • 0
    @nothappy sure! it's leksyib14
  • 0
    @nothappy seen the invite, what file?
  • 1
    @leksyib Contact.jsx
  • 1
    @nothappy okay I just raised a merge request
  • 0
    @leksyib I'll make a different branch and merge it
Add Comment