Home > Software engineering >  How to access rtk query function globally
How to access rtk query function globally

Time:04-03

I use RTK Query, and want to register.

If the user clicks on submit then the Button should named "isLoading...".

So how can I do this?

So I can not access the isLoading from useRegisterQuery, and if I put it outside of the function then it actions directly

const Register = () => {
const [input, setInput] = useState('');

 const submitForm = () => {
     const { data, error, isLoading } = useRegisterQuery();
 }

return (
  <View>
    <TextInput value={input} onChangeText={(e) => setInput(e)} />
    
    <Pressable>
      <Text>{isLoading ? 'isLoading' : 'Register'}</Text>
    </Pressable>
  </View>
)
};

CodePudding user response:

You cannot call hooks conditionally/programmatically based on an action, like a submit form button. Similar to Alvar's suggestion, see https://reactjs.org/docs/hooks-rules.html#only-call-hooks-at-the-top-level for specs.

To fix this, you just need to move the hook so that it's always going to run aka at the top level of the function's scope. You may see a similar/the same issue with a console error "Rendered more hooks than during the previous render".

const Register = () => {
const [input, setInput] = useState('');
const { data, error, isLoading } = useRegisterQuery();

 const submitForm = () => {

   // Do whatever with data, error, isLoading ect
 }

return (
  <View>
    <TextInput value={input} onChangeText={(e) => setInput(e)} />
    
    <Pressable>
      <Text>{isLoading ? 'isLoading' : 'Register'}</Text>
    </Pressable>
  </View>
)
};

CodePudding user response:

Do not use hook in a regular javascript function. Read why here.

I would let useRegisterQuery also return a submitForm function which you call on button press.

  • Related