I am trying to use react-mentions library which has a onAdd function as a prop which is fired once user selects a value from the suggestions that are rendered. I've leveraged hooks for the same but when I set the value of comment the data is stale inside the onAdd function even if it is invoked after the onChange event is triggered. Here is the code snippet for the same
import React, { useState, useEffect } from "react";
import { MentionsInput, Mention } from "react-mentions";
const MyComponent = props => {
let [comment, setComment] = useState("");
function onAdd(id, display) {
// Do something here
console.log("Comment inside onAdd: ", comment);
}
function handleCommentChange(e) {
// Handle the changes in the textArea
console.log("from handleCommentChange: ", e.target.value);
setComment(e.target.value);
}
function renderSuggestion(entry, search, highlightedDisplay, index, focused) {
// Modify the suggestion dropdown by returning valid JSX
return (
<>
<span>{entry.display}</span>
</>
);
}
function handleSubmitComment(e) {
e.preventDefault();
// Do something to submit comment
}
return (
<>
<MentionsInput
markup="@[__display__](__id__)"
value={comment}
onChange={handleCommentChange}
placeholder={"Mention people using '@'"}
>
<Mention
trigger="@"
data={[{
id: "1",
display: "Jimmy"
},
{
id: "2",
display: "Ketut"
},
{
id: "3",
display: "Gede"
}]}
renderSuggestion={renderSuggestion}
onAdd={onAdd}
appendSpaceOnAdd={true}
/>
</MentionsInput>
<button onClick={handleSubmitComment}>Comment</button>
</>
);
};
export default MyComponent;
Now when I check the from handleCommentChange console.log it has value @Jimmy if i select Jimmy but inside onAdd function it is still @
Which was previous value of the comment and not the current value. I am new to react hooks and would like to know what am i missing here?