react useState() not updating state as expected

Viewed 18
const [refreshBtnClicked, setRefreshBtnClicked] = React.useState(false);

const refreshClicked = () => {
    setRefreshBtnClicked(true);
    fetchAnalytics();
}

 const fetchAnalytics = async () => {
        setLoading(true);
        try{
            let analyticsResponse = await Axios({
                method: 'post',
                url: process.env.REACT_APP_BEATS_GENERAL_REPORT,
                headers: {
                    "Access-Control-Allow-Origin": "*",
                    Authorization: "Bearer " + sessionStorage.getItem("idToken")
                },
                data: formData
            })
            setAnalyticsData(analyticsResponse.data);
            setShowCards(true);
            refreshBtnClicked && ToastSuccess('Updated successfully');
            setRefreshBtnClicked(false);
            setLoading(false);
        }catch(err){
            console.log(err);
            ToastError('Error while fetching data');
            setLoading(false);
        }
    }

i need to show the toast if refreshBtnClicked is true even though i set it to be true when the refresh button is clicked It still shows the state as false . But i am setting the state as false after the toast is displayed. can't understand y..

1 Answers

Because setState is asynchronous and you immediately invoke fetchAnalytics, so the new state is not yet available to it.

refreshBtnClicked doesn't need to be state at all; in fact you don't need the value at all since you can just await for the fetch to complete, and toast in the refresh clicked function.

const refreshClicked = async () => {
  await fetchAnalytics();
  ToastSuccess("Updated successfully");
};

const fetchAnalytics = async () => {
  setLoading(true);
  try {
    let analyticsResponse = await Axios({
      method: "post",
      url: process.env.REACT_APP_BEATS_GENERAL_REPORT,
      headers: {
        "Access-Control-Allow-Origin": "*",
        Authorization: "Bearer " + sessionStorage.getItem("idToken"),
      },
      data: formData,
    });
    setAnalyticsData(analyticsResponse.data);
    setShowCards(true);
    setLoading(false);
  } catch (err) {
    console.log(err);
    ToastError("Error while fetching data");
    setLoading(false);
  }
};
Related