Search code examples
reactjsreduxredux-toolkitrtk-query

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?


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