khrzstoper
khrzstoper

Reputation: 41

How to use synchronous and asynchronous functions inside onClick method in React

I have a react component with this state

const [name, setName] = useState('')
const [comment, setComment] = useState('')
const [notes, setNotes] = useState([])

this function handles the input elements to fill the order

const handleComments = () => {
 setNotes([...notes, {
  name,
  comment
 }])
 setName('')
 setComment('')
}

and this function sends the info to the server

const update = async () => {
 const newNotes = notes.map(note => ({
  name,
  comment 
 }))
 return updateNotesPromise(newNotes)
}

here I have a button that has to execute both functions

<Button onClick={} /> 

How can I create a function that is passed through the onClick method and executes handleComments in order to load the info on the DOM and then, once that info there, executes the update function and saves the order info into the DB ?

Upvotes: 1

Views: 1366

Answers (2)

Hao Wu
Hao Wu

Reputation: 20724

Here's a way to handle the component updating and server communicating with error handling:

const onButtonClicked = useCallback(async (name, comment) => {
  // cache the olds notes
  const oldNotes = [...notes];

  // the updated notes
  const newNotes = [...notes, {
    name,
    comment
  }];

  // update the component and assume the DB save is successful
  setNotes(newNotes);

  try {
    // update the data to DB
    await updateNotesPromise(newNotes);
  } catch(ex) {
    // when something went wrong, roll back the notes to the previous state
    setNotes(oldNotes);
  }
}, [notes]);

Upvotes: 1

Pavlos Karalis
Pavlos Karalis

Reputation: 2966

It looks like you're using functional components, so you can create a useEffect that makes an API put request whenever notes gets updated:

useEffect(()=> {
  updateNotesPromise(notes); 
},[notes])

I'm assuming updateNotesPromise is a function that makes your request call? It's also unclear why newNotes is being mapped from notes, or why update is async when it doesn't await anything. Your onClick would simply trigger handleNotes (I'm assuming that is your submit button).

Upvotes: 1

Related Questions