In my React project using React Query, I have a functional component MoveKeywordModal
such that:
when it first loads, it fetches from API endpoint
api/keyword_lists
to fetch a bunch ofkeywordLists
data. For each of thesekeywordLists
, call itlist
, I create a clickable element.When the clickable element (wrapped in a
HoverWrapper
) gets clicked, I want to send a POST API request toapi/keyword_lists/:list_id/keyword_list_items/import
with some data. where:list_id
is the id of the list just clicked.
export const MoveKeywordModal = ({
setShowMoveKeywordModal,
keywordsToMove
}) => {
const { data: keywordLists } = useQuery('api/keyword_lists', {})
const [newKeywordList, setNewKeywordList] = useState({})
const { mutate: moveKeywordsToList } = useMutation(
`api/keyword_lists/${newKeywordList.id}/keyword_list_items/import`,
{
onSuccess: data => {
console.log(data)
},
onError: error => {
console.log(error)
}
}
)
const availableKeywordLists = keywordLists
.filter(l => l.id !== activeKeywordList.id)
.map(list => (
<HoverWrapper
id={list.id}
onClick={() => {
setNewKeywordList(list)
moveKeywordsToList({
variables: { newKeywordList, data: keywordsToMove }
})
}}>
<p>{list.name}</p>
</HoverWrapper>
))
return (
<>
<StyledModal
isVisible
handleBackdropClick={() => setShowMoveKeywordModal(false)}>
<div>{availableKeywordLists}</div>
</StyledModal>
</>
)
}
Despite calling setNewKeywordList(list)
in the onClick
of the HoverWrapper
, it seems the newKeywordList.id
is still not defined, not even newKeywordList
is defined.
What should I do to fix it?
Thanks!
question from:https://stackoverflow.com/questions/65649154/react-query-usemutation-set-mutationkey-dynamically