Home > Enterprise >  React Loader doesn't start before http request
React Loader doesn't start before http request

Time:11-18

I have one react app and inside this app I want to start my loader before request and finish after response But it is not working . Firstly I thought state change not working but when I delete state value after response then I recognized that it is changing state value and loader starting.

 state.isLoad = true;
    console.log(state)
    const url =
      "https://apiurl/testocr/api/v1/Documents/"  
      state.controls.entity!.value  
      "/custom-workflow";

    axios
      .post(url, formData, {
        auth: { username: "username", password: "pass" },
      })
      .then((data) => {
        console.log(data);
        dispatch(
          actions.handleNotification(
            data.data.message == null ? "Success" : data.data.message,
            NotificationType.Info
          )
        );
        state.isLoad=false;

      })
      .catch((_) => {
        console.log(_);
        state.isLoad = false;
        dispatch(
          actions.handleNotification("Error happened", NotificationType.Error)
        );
      });

isLoad in state if used for changing element which will be shown

{state.isLoad ? (
        <Loader />
      ) : (
        <Container style={{ backgroundColor: "#fff", padding: "2em" }}>  </Container>
      )}

State changing is not working until response comes when response comes then state is changing and here if I delete state.isLoad=false; from code then loader comes. What is my missing? How can enable loader before request and finish loader after response

Thanks in advance

CodePudding user response:

setState({ ...state, isLoad:false });

rather than

state.isLoad:false

is working for me

CodePudding user response:

for changing state, you have to use setState function

setState({
...state,
isLoad: false
},()=> console.log(state))

CodePudding user response:

Yes @pc_coder and you can even make it more clear api call using .finally() and stop loading there instead of each time in .then() and .catch() block

state.isLoad = true; // use it as reactive state in constructor like this.state={isLoad:true}
console.log(state)
const url =
  "https://apiurl/testocr/api/v1/Documents/"  
  state.controls.entity!.value  
  "/custom-workflow";

axios
  .post(url, formData, {
    auth: { username: "username", password: "pass" },
  })
  .then((data) => {
    console.log(data);
    dispatch(
      actions.handleNotification(
        data.data.message == null ? "Success" : data.data.message,
        NotificationType.Info
      )
    );

  })
  .catch((_) => {
    console.log(_);
    dispatch(
      actions.handleNotification("Error happened", NotificationType.Error)
    );
  }).finally{
      this.setState(state=>({...state,isLoad:false}))
  };
  • Related