Home > Software design >  running setState right before submit is not submitting the correct information due to it being async
running setState right before submit is not submitting the correct information due to it being async

Time:04-04

I am trying to run a function before setting state when the user clicks submit, but due to it being asynchronous I'm not getting the information that I'm looking for. The function splits a string into an array that is then set in state right before submit:

const [post, setPost] = useState({ title: '', description: '', tags: [] });
const [tagInput, setTagInput] = useState('');

const handleSubmit = (e) => {
    e.preventDefault();
    setPost((prevState) => ({
      ...prevState,
      tags: [
        ...tagInput
          .split(',')
          .splice(2)
          .map((value) => value.trim().replace(/[\W_] /g, '')),
      ],
    }));
   createPost(post)
          .then((response) => console.log(response))
          .catch((err) => console.log(err));
};

these values are coming from an input that holds 'tags' that the user submits.

<input
  type='text'
  placeholder='politics, humanitarian, nationalParks'
  name='tags'
  className='post-form-input'
  value={tagInput}
  onChange={handleTagInput}
/>

the value of that input is set to another state:

const [tagInput, setTagInput] = useState('');

which as shown above is then parsed and set into my 'post' state. onSubmit() I'm losing the tags, they aren't saving. How can I implement this to get the array to save?

CodePudding user response:

I can think of three options you could do:

  1. Remove the createPost part from handleSubmit, create a useEffect that depends on post and if post is valid you send them from there.
  2. Create a useEffect that depends on tagInput and updates post accordingly, so post would be ready when you submit.
  3. Update post directly from handleTagInput, which I guess sets the tagInput, and post also would be ready on submit.
  • Related