Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

In my React project using React Query, I have a functional component MoveKeywordModal such that:

  1. when it first loads, it fetches from API endpoint api/keyword_lists to fetch a bunch of keywordLists data. For each of these keywordLists, call it list, I create a clickable element.

  2. When the clickable element (wrapped in a HoverWrapper) gets clicked, I want to send a POST API request to api/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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
573 views
Welcome To Ask or Share your Answers For Others

1 Answer

react doesn’t perform state updates immediately when you call the setter of useState - an update is merely 'scheduled'. So even though you call setNewKeywordList, the newKeywordList will not have the new value in the next line of code - only in the next render cycle.

So while you are in your event handler, you’ll have to use the list variable:

setNewKeywordList(list)
moveKeywordsToList({
    variables: { newKeywordList: list, data: keywordsToMove }
 })

/edit: I just realized that your call to useMutation is not correct. It doesn’t have a key like useQuery, it has to provide a function as the first argument that takes variables, known as the mutation function:

  const { mutate: moveKeywordsToList } = useMutation(
    (variables) => axios.post(`api/keyword_lists/${variables.newKeywordList.id}/keyword_list_items/import`),
    {
      onSuccess: data => {
        console.log(data)
      },
      onError: error => {
        console.log(error)
      }
    }
  )

see also: https://react-query.tanstack.com/guides/mutations


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...