Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use await for get request in RTKQuery?

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:

  • Approaches for using RTK-Query hooks inside functions?
  • https://www.reddit.com/r/reduxjs/comments/pvvpwy/is_there_a_way_to_await_for_an_rtk_query_response/

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...!!

like image 924
lainNao Avatar asked Jan 26 '26 15:01

lainNao


1 Answers

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));
like image 62
Liko Avatar answered Jan 28 '26 22:01

Liko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!