0

I am trying to redirect to another page after fetch GET call from Modal from in react using history.props and I redirected but I don't know what should write there to show my actual data. I editied somehting i added something in history.props and componentDidMount in Report Here is my code:

import React, { Component } from "react";
import Datee from "./Date";
import { withRouter } from "react-router";

export class CarReports extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectOptions: [],
      movie: [],
      mov: "",
      query: "",
      results: []
    };

    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleChange = this.handleChange.bind(this);
  }



  async handleSubmit(e) {
    let authToken = localStorage.getItem("Token");
    try {
      const from = e.target.elements.from.value;
      const to = e.target.elements.to.value;
      const selections = [...e.target.elements.selectOptions.options].filter(
        opt => opt.selected
      );
      const selectedValues = selections.map(opt => opt.value);
      const selectedString = selectedValues.join(",");
      e.preventDefault();
      const res = await fetch(
        `http://localhost:8000/api/1/deliveries/report/?date__lte=${to}&date__gte=${from}&user=${selectedString}`,
        {
          method: "GET",
          headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
            Authorization: "Bearer " + JSON.parse(authToken)
          }
        }
      );
      const movie = await res.json();
      console.log(movie);
      this.setState({
        movie
      });
      this.props.history.push({
    pathname: "/carreport",
    state: movie
  });
    } catch (e) {
      console.log(e);
    }

  }

  handleChange = e => {
    let target = e.target;
    let name = target.name;
    //here
    let value = Array.from(target.selectedOptions, option => option.value);
    this.setState({
      [name]: value
    });
  };

  render() {
    return (
      <div id="car" class="modal">
        <a
          href="# "
          rel="modal:close"
          className="float-right text-white h4"
          style={{
            background: "#b71c1c",
            borderRadius: "50%",
            padding: "10px",
            height: "32px",
            lineHeight: "10px"
          }}
        >
          &times;
        </a>
        <p className="mod" style={{ marginTop: "40px" }}>
          CARS REPORT
        </p>

        <form style={{ marginTop: "20px" }} onSubmit={this.handleSubmit}>
          <div>
            <Datee />
          </div>
          <div className="form-group" style={{ marginTop: "20px" }}>
            <label style={{ opacity: "0.6", fontSize: "10px" }}>
              CHOOSE A CAR
            </label>
            <select
              name="selectOptions"
              style={{ width: "390px" }}
              multiple={true}
              onChange={this.handleChange}
              value={this.state.selectOptions}
              class="form-control"
            >
              <option value="1">Choose Car From List</option>
              <option value="1">General Score</option>
              <option value="2">Dynamic</option>
              <option value="3">Speed</option>
              <option value="4">Fuel Save</option>
            </select>
          </div>

          <div style={{ marginTop: "50px" }}>
            <center>
              <button
                type="submit"
                value="Get Data"
                className="btn btn-login text-white font-weight-bolder boxx "
                style={{
                  height: "40px",
                  fontSize: "13px",
                  lineHeight: "30px",
                  width: "200px",
                  background: "rgba(183, 28, 28, 1)",
                  border: "none",
                  color: "white",
                  margin: "auto"
                }}
              >
                RAPORT
              </button>
            </center>
          </div>
        </form>
      </div>
    );
  }
}

export default withRouter(CarReports);

Here is my careport.js page where I want to display data. I don't know what to do here.

import React, { Component } from "react";
import ReactToExcel from "react-html-table-to-excel";
import CarReports from "../CarReports";

class Report extends Component {

componentDidMount() {
    const movie = this.props.location.state.movie;
    this.setState({
      movie
    });
    console.log(movie)
  }

  render() {
    return (
      <div className="container" style={{ marginTop: "50px" }}>
        <CarReports />
        <div className="headerr" style={{ marginTop: "25px" }}>
          <h6>CAR REPORT</h6>
          <p className="p">From 12-17-2019 To 12-12-2019</p>
          <div className="driver report">
            <table className="table" id="table-to-xls">
              <thead>
                <tr>
                  <th>No</th>
                  <th>Full Name</th>
                  <th>Car Quantity</th>
                  <th>Mileage[Km]</th>
                  <th>Fuel Consumed[L]</th>
                  <th className="t">
                    Average Fuel<br></br> Consumed[L/100km]
                  </th>
                  <th className="t">Overspeed Distance[%]</th>
                  <th className="t">
                    Critical <br></br>Overspeed [qty.]
                  </th>
                  <th>Score: Overall</th>
                </tr>
              </thead>

              <tfoot>
                <tr className="thead">
                  <th></th>
                  <th>Summary</th>
                  <th></th>
                  <th></th>
                  <th></th>
                  <th></th>
                  <th></th>
                  <th></th>
                  <th></th>
                </tr>
              </tfoot>
            </table>

            <div style={{ marginTop: "40px" }}>
              <center>
                <a className="btn" href="#car" rel="modal:open" id="bttt">
                  NEW REPORT
                </a>

                <ReactToExcel
                  className="btn btn-success btn-lg bb"
                  table="table-to-xls"
                  filename="SoftbikeReport"
                  sheet="sheet 1"
                  buttonText="EXPORT CSV"
                />
              </center>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

export default Report;
rahul raj
  • 1
  • 4
  • You could use context to pass the state on rerouting like this: [link](https://stackoverflow.com/questions/39847360/how-to-pass-state-props-when-redirecting-to-another-route-in-react) Or you could setup a Redux store to keep global state and use it in different routes in your app. This is probably a better solution for more complex state objects. – kbo Nov 26 '19 at 13:41

1 Answers1

0

You can pass state when redirecting using react-router's state API like so:

/** INSIDE CarReports.jsx */
export class CarReports extends Component {
  ...
  async handleSubmit() {
    ...
    const res = await fetch(...);
    ...
    const movie = await res.json();
    this.setState({ movie });
    this.props.history.push({
      pathname: "/carreport",
      state: movie
    });
  }
  ...
}

You can then access the fetch results inside CarReport.jsx like so:

export class CarReport extends Component {
  componentDidMount() {
    const movie = this.props.location.state.movie;
  }
  ...
}

here are some more resources:

How do i pass state through React_router?

https://tylermcginnis.com/react-router-pass-props-to-link/

JohnCdf
  • 858
  • 1
  • 7
  • 27
  • Hey , I tried this but i am getting error i tried like this `componentDidMount() { const movie = this.props.location.state.movie; this.setState({ movie }); console.log(movie) }` @JohnCdf – rahul raj Dec 02 '19 at 12:32