How to use await for get request in RTKQuery?
Asked Answered
P

1

13

I've tried

  • initiate - but this result was retrieved from previous result.
  • mutate - but I think this is irregular.

Is there any way to use await for a normal get request?

relevant questions:


Specifically, I want to do the following:

useEffect(() => {
  someRTKQuerysGetMethod()
    .then(data => setValuesToForm(data))
}, [])

However, the comment I received from phry may have solved the problem.

  • I updated to v1.7
  • use "useLazyQuery" and unwrap()
const [getPokemon] = useLazyGetPokemonQuery()

useEffect(() => {
  getPokemon({...})
    .unwrap()
    .then(data => setValuesToForm(data))
}, [])

Thank you very much...!!

Partin answered 12/12, 2021 at 8:23 Comment(3)
Can you please add a little more info on what you actually want to do in which context? Right now the answer could be anything from "yes, initiate, but please upgrade to RTK 1.7" to "use useLazyQuery, but upgrade to RTK 1.7".Excurvature
@Excurvature Thank you for your kind comment. I added more info. But today, I read your comment and I updated the version, and I could what I wanted. Thank you very much..!Partin
redux-toolkit.js.org/rtk-query/api/created-api/…Sanctity
O
17

You can use the useLazyQuery hook with the unwrap method.

// Get the trigger
const [getPokemon] = useLazyGetPokemonQuery();
    
// Then you can call with await
await getPokemon().unwrap();
    
// Or with standard promise
getPokemon()
  .unwrap()
  .then((fulfilled) => console.log(fulfilled))
  .catch((rejected) => console.error(rejected));
Ontina answered 11/10, 2022 at 23:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.