Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

RTK query isSuccess on first api call is always false

So I am doing a form validation onBlur and I am using RTK query for calling the api. The problem I am facing is that on the very first API call the isSuccess is returning false even though the API return status is 200

const [validateUser, { data, isSuccess }] = authAPI.useValidateUserMutation();
  const validateUserDetails = (name, event) => {
    event.preventDefault();
    if (event.target.value !== "") {
      let fieldData = {
        fieldName: name,
        value: event.target.value,
      };
      validateUser(fieldData);
      console.log("Is Success: ", isSuccess);
      if (isSuccess && data.errors.status !== 200) {
        console.log(data);
      }
    } else {
    }
  };

During the first time validating
enter image description here

Even though the status is API status is 200 success is returned false but now if I do it again it will return true
enter image description here
Is there a way to solve this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The isSuccess variable you are referring to here is the variable created by the closure of the render before you executed validateUser. As a consequence, at some point in the future the whole component will rerender and create a new closure. In that new closure, there will also be a isSuccess variable, and that new variable will be true. But that old isSuccess variable is a "snapshot from the past", a value in a closure that will never change.
This is a concept that will happen in React a lot, independently of RTK Query, so you probably better read up on closures.

What you could do here, instead of accessing closure variables, is something along these lines:

const validateUserDetails = async (name, event) => {
    event.preventDefault();
    if (event.target.value !== "") {
      let fieldData = {
        fieldName: name,
        value: event.target.value,
      };
      try {
        const data =  await validateUser(fieldData).unwrap();
        // do something with it
      } catch (error) {
        // do something with it
      }
  };
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading