Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass state to another component using useHistory?

I need to pass the state from the useState hook to another component, but the only connection between them is one button that has an onClick function to history. push(route).

Table Page (from this page I must send state to TableMore page below)

import React, { useState, useEffect } from "react";
import { useTable, usePagination } from "react-table";
import { useHistory } from "react-router-dom";
import styled from "styled-components";
import apiRequest from "helpers/apiRequest";
import Header from "../../../components/Header/Header";

function Table({ columns, data, searchData, setsearchData, getData }) {
  // Use the state and functions returned from useTable to build your UI
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    prepareRow,
    page, // Instead of using 'rows', we'll use page,
    // which has only the rows for the active page

    // The rest of these things are super handy, too ;)
    canPreviousPage,
    canNextPage,
    nextPage,
    previousPage,
    rows,
  } = useTable(
    {
      columns,
      data,
      searchData,
      setsearchData,
      getData,
      initialState: { pageIndex: 0 },
    },
    usePagination
  );

  // Render the UI for your table
  return (
    <>
      <div className="inputs">
        <Input
          type="text"
          placeholder="Unesi ime "
          onChange={(e) =>
            setsearchData({ ...searchData, ime: e.target.value })
          }
          onKeyPress={(e) => (e.key === "Enter" ? getData() : null)}
        />
        <Input
          type="text"
          placeholder="Unesi ime oca "
          onChange={(e) =>
            setsearchData({ ...searchData, imeOca: e.target.value })
          }
          onKeyPress={(e) => (e.key === "Enter" ? getData() : null)}
        />
        <Input
          type="text"
          placeholder="Unesi prezime "
          onChange={(e) =>
            setsearchData({ ...searchData, prezime: e.target.value })
          }
          onKeyPress={(e) => (e.key === "Enter" ? getData() : null)}
        />
        <Button onClick={() => getData()}>Pretraži</Button>
      </div>
      <table {...getTableProps()}>
        <thead>
          {headerGroups.map((headerGroup) => (
            <tr {...headerGroup.getHeaderGroupProps()}>
              {headerGroup.headers.map((column) => (
                <th {...column.getHeaderProps()}>{column.render("Header")}</th>
              ))}
            </tr>
          ))}
        </thead>
        <tbody {...getTableBodyProps()}>
          {page.map((row, i) => {
            prepareRow(row);
            return (
              <tr {...row.getRowProps()}>
                {row.cells.map((cell) => {
                  return (
                    <td {...cell.getCellProps()}>{cell.render("Cell")}</td>
                  );
                })}
              </tr>
            );
          })}
        </tbody>
      </table>

      <div className="pagination">
        <span>
          Prikazuje se
          <strong>{rows.length} od 8000</strong> rezultata
        </span>
        <div className="buttons">
          <Button onClick={() => previousPage()} disabled={!canPreviousPage}>
            Prethodna stranica
          </Button>
          <Button onClick={() => nextPage()} disabled={!canNextPage}>
            Sljedeća stranica
          </Button>
        </div>
      </div>
    </>
  );
}

const TablePage = () => {
  const [tableData, setTableData] = useState([]);
  const [searchData, setsearchData] = useState({
    ime: "",
    prezime: "",
    imeOca: "",
  });
  const [data, setData] = useState({
    email: "",
    password: "",
  });
  const [token, setToken] = useState("");
  const [clicked, setClicked] = useState(false);
  const [dataId, setdataId] = useState("");
  const history = useHistory();
  let success = false;
  if (token) {
    success = true;
  } else {
    success = false;
  }

  const getData = async () => {
    const { ime, prezime, imeOca } = searchData;
    try {
      const response = await apiRequest({
        method: "get",
        url: `v1/spisak-srebrenica?prezime=${prezime}&ime=${ime}&imeOca=${imeOca}`,
      });
      if (response.status === 200) {
        setTableData(response.data);
      }
    } catch (err) {
      console.log(err);
    }
  };
  const getToken = async () => {
    await apiRequest({
      method: "post",
      url: `auth/login`,
      data,
    })
      .then((resp) => {
        console.log(resp.data);
        setToken(resp.data.token);
      })
      .catch((err) => {
        console.log(err.response.data);
      });
  };

  useEffect(() => {
    getData();
  }, []);

  const columns = [
    {
      Header: "ID ŽRTVE",
      accessor: "id_grobnog_mjesta",
    },
    {
      Header: "IME (OCA) PREZIME",
      accessor: "ime_prezime",
    },
    {
      Header: "GODINA ROĐENJA",
      accessor: "godina_rodjenja",
    },
    {
      Header: "VIŠE",
      Cell: ({ row }) => (
        <Button
          position="table"
          onClick={() =>
            history.push(`tablemore/${row.values.id_grobnog_mjesta}`) ||
            setClicked(!clicked) ||
            setdataId(row.values.id_grobnog_mjesta)
          }
        >
          više
        </Button>
      ),
    },
  ];
  return (
    <div>
      <Header />
      {success ? (
        <Styles>
          <Table
            columns={columns}
            data={tableData}
            searchData={searchData}
            setsearchData={setsearchData}
            getData={getData}
          />
        </Styles>
      ) : (
        <Container>
          <div className="content">
            <h1>Prijavite se</h1>
            <div className="form">
              <input
                type="email"
                placeholder="Unesite email"
                onChange={(e) => setData({ ...data, email: e.target.value })}
              />
              <input
                type="password"
                placeholder="Unesite šifru"
                onChange={(e) => setData({ ...data, password: e.target.value })}
              />
              <button onClick={getToken}>Prijavi se</button>
            </div>
          </div>
        </Container>
      )}
    </div>
  );
};

export default TablePage;

As you can see, onClick={() => history.push(tablemore/${row.values.id_grobnog_mjesta})} is where I am let say calling tablemore page. So I don't know how to pass the TOKEN to table more page.

like image 675
bajrax Avatar asked Oct 14 '22 19:10

bajrax


1 Answers

With react-router-dom v6, you can set location state to useNavigate:

import { useNavigate } from "react-router-dom";
...
let navigate = useNavigate();
navigate("/users/123", { state: partialUser });

With react-router-dom v5 you can use useHistory:

import { useHistory } from "react-router-dom";
...
let history = useHistory();
history.push("/users/123", { state: partialUser });

And on the next page you can access it with useLocation:

 import { useLocation } from "react-router-dom";
 ...
 let location = useLocation();
 location.state;
like image 85
Vitaliy Rayets Avatar answered Oct 18 '22 13:10

Vitaliy Rayets