I use react-native.
And this is the function that I want to use.
The most important point here is editCommentMutation
.
In order to execute this mutation, it requires two variables which are id
and payload
.
const onUpdateComment = React.useCallback((commentId) => {
setEdit(true);
console.log(commentId, comments);
editCommentMutation({
variables: {
id: parseInt(commentId),
payload: comments,
},
});
}, []);
I get these two variables correctly.
For id
, I get it from component screen. So It comes thru argument
.
For payload
, I get it on the same screen.
Problem here is when I press button1
, it sends commentId(id)
data from component screen to this page.
And when I press button2
, it sends comments(payload)
data on this page.
On this App, I press button1 and write comments then button2 in order.
So Each data comes not together, but one by one.
So I execute console.log(commentId, comments)
,
- press button1 :
386 undefined
- press button2 :
undefined Object { "comments": "뭐야", }
It has undefined
for sure..
But in order to execute mutation, I need two data together.
For this, I need to save coming data in somewhere, I guess.
I also tried
const [data, setData] = useState("")
.
After I save coming commentId to here as:
setData(commentId)
.
But it isn't saved, just disappears. :)
Can you help me?
CodePudding user response:
Here is a minimal verifiable example. Run the code below and
- click ✏️ to edit one of the comments
- click ✅ to save your edit and view the updated comment
function App() {
const [edit, setEdit] = React.useState(null)
const [comments, setComments] = React.useState([ "hello", "안녕하세요" ])
const onEdit = editable => event => { setEdit(editable) }
const onUpdate = newComment => event => {
/* execute your graphql mutation here */
setComments([
...comments.slice(0, edit.index),
newComment,
...comments.slice(edit.index 1)
])
setEdit(null)
}
return <div>
{comments.map((comment, index) =>
<p>{comment}
<button
children="✏️"
onClick={onEdit({comment, index})}
disabled={Boolean(edit)}
/>
</p>
)}
{edit ? <EditComment text={edit.comment} onUpdate={onUpdate} /> : null}
</div>
}
function EditComment({ text, onUpdate }) {
const [value, setValue] = React.useState(text)
return <div>
<input value={value} onChange={e => setValue(e.target.value)} />
<button onClick={onUpdate(value)} children="✅" />
</div>
}
ReactDOM.render(<App/>, document.querySelector("#app"))
button[disabled] { opacity: 0.5; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.14.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.14.0/umd/react-dom.production.min.js"></script>
<div id="app"></div>
In your App you will execute your mutation in onUpdate
. A cancel button ❌ can easily be defined using const onCancel = event => { setEdit(null) }
and pass it to EditComment
.