universe11
universe11

Reputation: 1053

How to access rtk query function globally

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>
)
};

Upvotes: 0

Views: 695

Answers (2)

Mark
Mark

Reputation: 175

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>
)
};

Edit: Adding this article that demystifies react hooks and why they have such rules. tl;dr, hooks are stored in an array, if we don't get them in the same order between re-renders, we could end up with a reference to another object (ie different useState, etc) https://medium.com/@ryardley/react-hooks-not-magic-just-arrays-cd4f1857236e

Upvotes: 1

alvAro365
alvAro365

Reputation: 399

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.

Upvotes: 0

Related Questions