2

I'm a react beginner, so I don't know much, I tried to invoke a function where the JWT token is taken from the Local Storage and compared with that of from the backend, by sending an Axios request so that if I get a 200 response it means I can redirect it to another page, and while it is an error I can request the user to login. (please note that this is not a professional project but I need your help very much, guys)

The problem that I am facing is is the way that I set the OnClick in the cart button is correct? and how can I fix the React Hook Error that comes while maintaining this as a class? Unhandled Rejection (Error): Invalid hook call. Hooks can only be called inside of the body of a function component

import React, { Component } from "react";
import { Link, useHistory } from "react-router-dom";

import axios from "axios";

export default class NavBar extends Component {
  // eslint-disable-next-line
  constructor(props) {
    super(props);
  }
  
  async tokenizedCartRedirect() {
    var history = useHistory();
    var token = localStorage.getItem("currentToken");

    if (token != "") {
      const config = {
        headers: { "Content-Type": "application/json", "x-auth-token": token },
        mode: "cors",
      };
      const body = JSON.stringify(token);
      const res = axios
        .post("http://localhost:5000/auth", body, config)
        .then((res) => {
          history.push("/cart");
        })
        .catch((err) => {
          history.push("/login");
        });
    } else {
      history.push("/login");
    }
  }

  render() {
    //const element = (<div>Text from Element</div>)
    return (
      <header id="site-header" className="site-header__v7">
        <div className="topbar d-none d-md-block bg-punch-light">
          <div className="container">
            <div className="topbar__nav d-lg-flex justify-content-between align-items-center font-size-2">
              <ul className="topbar__nav--left nav ml-lg-n3 justify-content-center">
                <li className="nav-item">
                  <a href="#" className="nav-link text-dark">
                    <i className="font-size-3 glph-icon flaticon-question mr-2" />
                    Can we help you?
                  </a>
                </li>
                <li className="nav-item">
                  <a href="#" className="nav-link text-dark">
                    <i className="font-size-3 glph-icon flaticon-phone mr-2" />
                    +1246-345-0695
                  </a>
                </li>
              </ul>
            </div>
          </div>
        </div>
        <div className="masthead">
          <div className="bg-white border-bottom">
            <div className="container pt-3 pb-2 pt-lg-5 pb-lg-5">
              <div className="d-flex align-items-center position-relative flex-wrap">
                <div className="site-branding pr-md-11 mx-auto mx-md-0">
                  <Link to="/" className="d-block mb-1">
                    <img
                      src={require("../../assets/img/logo.png")}
                      className="img-fluid"
                      alt="image-description"
                      width="330px"
                    />
                  </Link>
                </div>
                <div className="site-search ml-xl-0 ml-md-auto w-r-100 flex-grow-1 mr-md-5 py-2 py-md-0">
                  <form className="form-inline my-2 my-xl-0">
                    <div className="input-group w-100">
                      <input
                        type="text"
                        className="form-control border-right-0 px-3"
                        placeholder="Search for comics by keyword"
                        aria-label="Amount (to the nearest dollar)"
                      />
                      <div className="input-group-append border-left">
                        <button
                          className="btn btn-dark px-3 rounded-0 py-2"
                          type="submit"
                        >
                          <i className="mx-1 glph-icon flaticon-loupe"></i>
                        </button>
                      </div>
                    </div>
                  </form>
                </div>
                <ul className="nav align-self-center d-none d-md-flex">
                  <li className="nav-item">
                    <a href="#" className="nav-link text-dark">
                      <i className="glph-icon flaticon-heart font-size-4"></i>
                    </a>
                  </li>
                  <li className="nav-item">
                    <Link
                      to="/login"
                      id="sidebarNavToggler"
                      role="button"
                      className="nav-link text-dark"
                      aria-controls="sidebarContent"
                      aria-haspopup="true"
                      aria-expanded="false"
                      data-unfold-event="click"
                      data-unfold-hide-on-scroll="false"
                      data-unfold-target="#sidebarContent"
                      data-unfold-type="css-animation"
                      data-unfold-overlay='{
                                          "className": "u-sidebar-bg-overlay",
                                          "background": "rgba(0, 0, 0, .7)",
                                          "animationSpeed": 500
                                      }'
                      data-unfold-animation-in="fadeInRight"
                      data-unfold-animation-out="fadeOutRight"
                      data-unfold-duration="500"
                    >
                      <i className="glph-icon flaticon-user font-size-4"></i>
                    </Link>
                  </li>
                  <li className="nav-item">
                    <dev
                      id="sidebarNavToggler1"
                      role="button"
                      className="nav-link pr-0 text-dark position-relative"
                      aria-controls="sidebarContent1"
                      aria-haspopup="true"
                      aria-expanded="false"
                      data-unfold-event="click"
                      data-unfold-hide-on-scroll="false"
                      data-unfold-target="#sidebarContent1"
                      data-unfold-type="css-animation"
                      data-unfold-overlay='{
                                          "className": "u-sidebar-bg-overlay",
                                          "background": "rgba(0, 0, 0, .7)",
                                          "animationSpeed": 500
                                      }'
                      data-unfold-animation-in="fadeInRight"
                      data-unfold-animation-out="fadeOutRight"
                      data-unfold-duration="500"
                    >
                      <i
                        className="glph-icon flaticon-icon-126515 font-size-4"
                        onClick={this.tokenizedCartRedirect()}
                      ></i>
                    </dev>
                  </li>
                </ul>
              </div>
            </div>
          </div>
          <div className="border-bottom py-3 py-md-0">
            <div className="container">
              <div className="d-md-flex position-relative">
                <div className="site-navigation mr-auto d-none d-xl-block">
                  <ul className="nav">
                    <li className="nav-item">
                      <Link
                        to="/"
                        className="nav-link link-black-100 mx-2 px-0 py-3 font-weight-medium active border-bottom border-primary border-width-2"
                      >
                        Home
                      </Link>
                    </li>
                    <li className="nav-item">
                      <Link
                        to="/products"
                        className="nav-link link-black-100 mx-2 px-0 py-3 font-weight-medium active border-bottom border-primary border-width-2"
                      >
                        Browse Comics
                      </Link>
                    </li>
                  </ul>
                </div>
                <div className="d-none d-md-block ml-md-auto secondary-navigation ">
                  <ul className="nav">
                    <li className="nav-item">
                      <a
                        href="#"
                        className="nav-link link-black-100 mx-2 px-0 py-3 font-weight-medium"
                      >
                        Subscription Pricing
                      </a>
                    </li>
                  </ul>
                </div>
              </div>
            </div>
          </div>
        </div>
      </header>
    );
  }
}

Natalia Kolisnyk
  • 287
  • 2
  • 10
  • useHistory is the hook that generates the error – Natalia Kolisnyk Sep 03 '20 at 06:36
  • Does this answer your question? [How to use Redirect in the new react-router-dom of Reactjs](https://stackoverflow.com/questions/43230194/how-to-use-redirect-in-the-new-react-router-dom-of-reactjs) –  Sep 03 '20 at 07:00

2 Answers2

0

You can not use hooks in class components

The hook useHistory will never work in a class, you need to move this outside the class to a wrapping functional component or convert this component to a functional component.

For a nice guide you should check out this article, It shows how to convert it step by step.

Example of how to use the hook

const MyComp = (props) => {
  const history = useHistory();

  const tokenizedCartRedirect = async (history) => {/* code */};

  return (
    <div>
      <SomeComponent onClick={() => tokenizedCartRedirect(history)} />
    </ div>
  )
}
Joe Lloyd
  • 19,471
  • 7
  • 53
  • 81
  • I tried to do that but then ** React Hook "useHistory" is called in function "tokenizedCartRedirect" which is neither a React function component or a custom React Hook function ** – Natalia Kolisnyk Sep 03 '20 at 07:08
  • 1
    @NataliaKolisnyk I've added an example to show you how you would use and pass history to the on click. – Joe Lloyd Sep 03 '20 at 07:15
0

Function components are a different way of creating a component in React, other than a Class.

Like in the example below:

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

You can have a good idea here: https://reactjs.org/docs/hooks-state.html

Guilhermevrs
  • 2,094
  • 15
  • 15