How to called async function in useEffect after submiting in react native?

Viewed 489

I would like once the user click on the submit button for the whole "page" to reload and the useEffect function to be called. The current behavior is that when the user clicks the submit button, the useEffect function is not called at all. It is as if it does not reload directly after submission. I don't know if this is due to async and await. I give you the code :

useEffect() :

useEffect(() => {

    console.log('test useEffect');

    (async () => {
      try {
        const value = await AsyncStorage.getItem('authToken_Lust');
        if(value !== null) {
          const decodedValue = jwt_decode(value);
          const current_time = Date.now() / 1000;
          if(decodedValue.exp < current_time) {
            setMessage('Vous n\'êtes plus connecté(e).')
          } else {
            setMessage('Vous êtes connecté(e)');
          }
        }
      } catch(err) {
        console.log(err);
      }
    })();

  }, []);

The code of the function called after the user clicks submit :

const onSubmit = async () => {
    setLoading(true)
    await fetch('http://192.168.1.36:3000/api/users/login', {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        email: email,
        password: password
      })
    })
    .then((response) => response.json())
    .then(async (res) => {
      if(res.error) {
        setMessage(res.error);
      } else {
        try {
          await AsyncStorage.setItem('authToken_Lust', res.token);
        } catch (err) {
          console.log(err);
        }
      }
    })
    .catch((err) => console.log(err))
    .finally(() => setLoading(false));
  }

Tanks

3 Answers

you need to make these changes to your codes:

const onSubmit = () => {
  setIsSubmitted(true);
  setLoading(true);
  fetch("http://192.168.1.36:3000/api/users/login", {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      email: email,
      password: password,
    }),
  })
    .then((response) => response.json())
    .then(async (res) => {
      if (res.error) {
        setMessage(res.error);
      } else {
        try {
          await AsyncStorage.setItem("authToken_Lust", res.token);
        } catch (err) {
          console.log(err);
        }
      }
    })
    .catch((err) => console.log(err))
    .finally(() => setLoading(false));
};
const asyncEffect = async () => {
  try {
    const value = await AsyncStorage.getItem("authToken_Lust");
    if (value !== null) {
      const decodedValue = jwt_decode(value);
      const current_time = Date.now() / 1000;
      if (decodedValue.exp < current_time) {
        setMessage("Vous n'êtes plus connecté(e).");
      } else {
        setMessage("Vous êtes connecté(e)");
      }
    }
  } catch (err) {
    console.log(err);
  }
};
useEffect(() => {
  if (isSubmitted) {
    console.log("test useEffect");
    asyncEffect();
  }
}, [isSubmitted]);
  1. Create a state variable to indicate that credentials have been successfully submitted (within this component).

    const [submitted, setSubmitted] = useState(1);
    
  2. Alter this state variable whenever you get a response from your api in onSubmit (to somehow update the component):

    try {
        await AsyncStorage.setItem('authToken_Lust', res.token);
        setSubmitted(submitted+1);
    }
    
  3. Remove the dependency array from your useEffect altogether or change it to respond to submitted value changes;

    useEffect(() => {
        // ...
    }, [submitted]);
    

I changed all my code taking into account your advice that gives :

const [submitted, setSubmitted] = useState(1);

useEffect(() => {
    console.log("test useEffect");
    asyncEffect();
  }, [submitted]);

  const asyncEffect = async () => {
    try {
      const value = await AsyncStorage.getItem("authToken_Lust");
      if (value !== null) {
        const decodedValue = jwt_decode(value);
        const current_time = Date.now() / 1000;
        if (decodedValue.exp < current_time) {
          setMessage("Vous n'êtes plus connecté(e).");
        } else {
          setMessage("Vous êtes connecté(e)");
        }
      }
    } catch (err) {
      console.log(err);
    }
  };

  const onSubmit = () => {
    setSubmitted(submitted+1);
    setLoading(true);
    fetch("http://192.168.1.36:3000/api/users/login", {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        email: email,
        password: password,
      }),
    })
    .then((response) => response.json())
    .then(async (res) => {
      if (res.error) {
        setMessage(res.error);
      } else {
        try {
          await AsyncStorage.setItem("authToken_Lust", res.token);
        } catch (err) {
          console.log(err);
        }
      }
    })
    .catch((err) => console.log(err))
    .finally(() => setLoading(false));
  };

When I click on the submit button, the console log works fine (I get "test useEffect" on console) but the asyncAffect() function does not seem to be called. The setMessage in asyncEffect () don't change at all.

Related