React make two async requests and passing the state

The problem with this is that, even when you updated the data inside the registerUser, you cannot get the updated data inside your registerUser until the next time you run it. This is due to the fact that most hooks will create a slice of the app state in one of its cycle and will not get the latest updated of the slice until it finish its cycle. You can read more about it here (it wrote about useEffect but same apply to useCallback ).

This is a nice example of what happen in your code, simplified version code

If you want to mitigate this issue, I suggest using useRef. This will ensure the data in your hooks always up-to-date

const dataRef = useRef({
  type: 2,
  email: "",
  name: "",
  password: "",
  company: "",
  role: "",
  phone: "",
  provider: "",
});
const registerUser = useCallback(async () => {
  if (data.provider === "") {
    const provider = await getProvider();
    if (!provider) {
      console.log("Get Provider Error");
      return;
    }
  }
  try {
    const res = await api.registerUser(dataRef.current);
    if (res.data.success) {
      history.push("/");
    }
  } catch (err) {
    console.log(err);
  }
});
const getProvider = useCallback(async () => {
  try {
    const res = await api.createUser({ TYPE: "S", TEXT1: data.name });
    if (res.data.TEXT3) {
      dataRef.current = { ...data, provider: res.data.TEXT3 };
      return res.data.TEXT3;
    }
  } catch (err) {
    return null;
  }
});

One note is that useRef won’t cause your component to re-render, so if you want your component your component to re-render when, let say your data get update then you should create a ref and a normal state and update both at the same time

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top