-1

I am using Axios for POST API in my project, so after I get back response from my server I want to navigate to other page by

this.props.history.push('/****')

but I always get error of TypeError: Cannot read property 'props' of undefined

Here is my code

class Banner extends Component {
  constructor(props) {
    super(props);
    this.state = {
      redirectToLogin: false,
      logout: false,
      loading: true,
    };
  }

   
  viewInsight = (item) => {
    let res;
    axios
      .post("https://webquickfix.com/controlcenter/get_banner_insight", {
        id: item._id,
      })
      .then(function(response) {
        console.log(response.status);
        console.log(response.data.data)
        localStorage.setItem(
          "bannerInsight",
          JSON.stringify(response.data.data)
        );

        if (response.status == 200) {
          this.props.history.push("/*****");
        }
      })
      .catch(function(error) {
        console.log(error);
        
      });

    
  };

  render() {

    return (
      <Container fluid className="main-content-container px-4">
        <div noGutters className="page-header py-4 contactUs">
          <PageTitle sm="4" title="Banners" className="text-sm-left" />
          <Button theme="danger" onClick={() => this.logout()}>
            Logout
          </Button>
        </div>

        <Row>
          <Col>
            <Card small className="mb-4">
              <CardHeader className="border-bottom">
                {" "}
                <h6 className="m-0">
                  All Banners{" "}
                  <button
                    title="Add Banner"
                    onClick={() =>
                      this.props.history.push("/controlcenter/add-banner")
                    }
                    className="btn ml-3 btn-primary"
                  >
                    <i className="fa fa-plus"></i>
                  </button>
                </h6>
              </CardHeader>
              <CardBody className="p-0 pb-3">
                <table className="table mb-0">
                  <thead className="bg-light">
                    <tr>
                      <th scope="col" className="border-0">
                        #
                      </th>
                      <th scope="col" className="border-0">
                        Banner Link
                      </th>
                      <th scope="col" className="border-0">
                        Webinar
                      </th>
                      <th scope="col" className="border-0">
                        Page
                      </th>
                      <th scope="col" className="border-0">
                        Insights
                      </th>
                      {/* <th scope="col" className="border-0">
                        Actions
                      </th> */}
                    </tr>
                  </thead>
                  <tbody>
                    {this.state.banners.map((item, index) => {
                      return (
                        <tr>
                          <td>{index + 1}</td>
                          <td>
                            <img src={item.image} style={{ width: 200 }} />
                          </td>
                          <td>
                            {item.isWebinar
                              ? this.props.webinars.filter(
                                  (webinar) => webinar._id == item.webinar_id
                                )[0].title
                              : ""}
                          </td>
                          <td>{item.page}</td>
                          <td
                            className="insightsBanner"
                            onClick={() => this.viewInsight(item)}
                          >
                            View Insights
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </CardBody>
            </Card>
          </Col>
        </Row>
      </Container>
    );
  }
}

export default Banner;

I have noticed an issue that if I use fetch instead of Axios then I am not getting this error, how could I make this work with Axios instead of fetch?

Here is the code if I use fetch:

let formData = new FormData();
    formData.append("id", item._id);
    fetch("https://webquickfix.com/controlcenter/get_banner_insight", {
      method: "POST",
      body: formData,
    })
      .then((response) => response.json())
      .then((responsejson) => {
        console.log(responsejson);
        if (responsejson.status === 200) {
          this.props.history.push("/*****");
        }
      });
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Ratnabh kumar rai
  • 1,426
  • 4
  • 21
  • 48

2 Answers2

1

You are using function as callback and not the arrow function so the context would not be the context of the react component. Use arrow function inside the then like this -

.then((response) => {
    console.log(response.status);
    console.log(response.data.data)
    localStorage.setItem(
      "bannerInsight",
      JSON.stringify(response.data.data)
    );

    if (response.status == 200) {
      this.props.history.push("/*****");
    }
  })
1

Try this:

const options = {
    url: 'https://webquickfix.com/controlcenter/get_banner_insight',
    method: 'POST',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json;charset=UTF-8'
    },
    data: {
        id: item._id
    }
}

axios(options)
   .then((response) => response.json())
   .then((responsejson) => {
       console.log(responsejson);
       if (responsejson.status === 200) {
           this.props.history.push("/*****");
       }
});
Steven2105
  • 540
  • 5
  • 20