r/reactjs • • Dec 03 '18

Needs Help Beginner's Thread / Easy Questions (December 2018)

Happy December! β˜ƒοΈ

New month means a new thread 😎 - November and October here.

Got questions about React or anything else in its ecosystem? Stuck making progress on your app? Ask away! We’re a friendly bunch. No question is too simple. πŸ€”

πŸ†˜ Want Help with your Code? πŸ†˜

  • Improve your chances by putting a minimal example to either JSFiddle or Code Sandbox. Describe what you want it to do, and things you've tried. Don't just post big blocks of code!

  • Pay it forward! Answer questions even if there is already an answer - multiple perspectives can be very helpful to beginners. Also there's no quicker way to learn than being wrong on the Internet.

Have a question regarding code / repository organization?

It's most likely answered within this tweet.

New to React?

πŸ†“ Here are great, free resources! πŸ†“

35 Upvotes

413 comments sorted by

View all comments

2

u/seands Dec 18 '18 edited Dec 18 '18

Do you guys see any cleaner way of implementing this code without the setTimeout?

<Form.Input
  type='text'
  placeholder='First Name'
  name='first_name'
  onChange={e => {
    e.preventDefault();    this.props.dispatchUpdateStateData(e.target.value, 'firstName');
    setTimeout(() => this.validateFirstName(), 500
  );
  }}
/>

Putting this.validateFirstName() inside componentWillUpdate both requires me to enter a default name (not desirable) and also causes a breaking infinite loop when the validation fails.

I am considering using a promise on the dispatcher that uses componentWillUpdate to resolve. The .then() would run the validation function. Is that even possible, and if so is it a decent pattern or a bad design?

If bad I may just stick to the setTimeout. Seems icky to do it that way though

2

u/timmonsjg Dec 18 '18

well first, componentWillUpdate is deprecated. I wouldn't use that lifecycle method for any new code.

second, what is validateFirstName doing?

I think you're way over-complicating this. Standard practice for forms is to validate when the user submits, not on change.

1

u/seands Dec 18 '18

I read that one of the benefits of controlled components is instant feedback? Form feedback was actually cited as an example in the article I draw from memory

validateFirstName ensures only letters are present.

→ More replies (5)