Home > Net >  React state update and display new value
React state update and display new value

Time:12-02

I am trying to update a state value and display that updated value in an input field, but nothing seems to work for me.

I have been going through various articles and answers but none of the ways seem to work for me, possibly I am doing something wrong.

const AnswerDetailOptions = ({ options, className, answer_id, last_review_details }) => {
  const [reviewNoteDisplay, setReviewNoteDisplay] = useState(last_review_details.note)
  const [reviewNoteTimeStamp, setReviewNoteTimeStamp] = useState(last_review_details.date_time)

  useEffect(() => {
    // test
  }, [reviewNoteDisplay])

  const submitReview = async () => {
    const payload = {
      note: reviewNote,
      answer_id
    }

    const response = await submitNewReview(payload)
    //console.log(response)

    if (response.status === 201) {
      toast.success('Review saved successfully')

      setReviewNoteDisplay(() => return response.data.data.note)
      setReviewNoteTimeStamp(() => return response.data.data.date_time)

      closeCreateReviewDialog()
    } else {
      toast.error('Failed to save review')
    }
  }

Render:

{
        reviewNoteTimeStamp ? 
          <>
            <EditableText 
              multiline="true"
              placeholder="Write a review..."
              defaultValue={reviewNoteDisplay}
              confirmOnEnterKey="true"
              onChange={(new_value) => setReviewNoteDisplay(new_value)}
              onConfirm={editReview}
            />
            <p className={classNames(styles.node, styles.reviewTimeStamp)}>{ format(new Date(reviewNoteTimeStamp), 'dd/MM/yyyy, hh:mm a') }</p>
            <Button onClick={() => setShowReviewHistory(true)}>Review History</Button>
          </> :
          <>
            <p>No reviews added</p>
          </>
      }

I am trying to get the new value of reviewNoteDisplay and reviewNoteTimeStamp but I keep geting the old value.

CodePudding user response:

your input needs to control the input, use value and not defaultValue here:

<EditableText 
 multiline="true"
 placeholder="Write a review..."
 value={reviewNoteDisplay}
 confirmOnEnterKey="true"
 onChange={(new_value) => setReviewNoteDisplay(new_value)}
 onConfirm={editReview}
/>

i don't know the EditableText component, but if onChange isn't fired on each key hit, you may also need to add:

onKeyUp={(e) => setReviewNoteDisplay(e.target.value)}

or something like this.

  • Related