Home > front end >  Variable is defined but never used warning javascript
Variable is defined but never used warning javascript

Time:04-29

Hi I'm making a login page in react and am sending the variables and login functions down to other files through <Component.Provider value={} /> method but it is not registering that I'm referring to variables above. How do I fix that?

enter image description here

Note: state is minimised but should be

var state = {
    token: null,
    userId: null,
};

Edit: Warning in text according to request

Code:

import React, { Component } from 'react';
import { BrowserRouter, Route} from 'react-router-dom';
import {Routes} from 'react-router-dom';
import {Navigate} from 'react-router-dom';
// import {Routes} from 'react-router-dom';
import './App.css';
import AuthPage from './pages/Auth';
import EventsPage from './pages/Events';
import BookingsPage from './pages/Bookings';
import MainNavigation from './components/Navigation/MainNavigation';
import AuthContext from './context/auth-context';



function App() {
     var state = {
        token: null,
        userId: null,
    };
    function login(token, userId, tokenExpiration) {
        this.setState({token: token, userId: userId});
    };
    function logout() {
        this.setState({token: null, userId: null})
    };
  return (
    <BrowserRouter>
     <React.Fragment>
         <AuthContext.Provider value={{ token: this.state.token, userId: this.state.userId, login: this.login, logout: this.logout }}>
      <MainNavigation />
       <main className="main-content">
         <Routes>
            <Route path="/" element={<Navigate to="/auth" replace={true}/>} />  
            <Route path="/auth" element={<AuthPage />} />
            <Route path="/events" element={<EventsPage/>} />
            <Route path="/bookings" element={<BookingsPage/>} />
         </Routes>
       </main>
         </AuthContext.Provider>
     </React.Fragment>
    </BrowserRouter>
  );
}

export default App;

Warning:

WARNING in src\App.js
  Line 1:17:   'Component' is defined but never used       no-unused-vars
  Line 16:10:  'state' is assigned a value but never used  no-unused-vars
  Line 20:14:  'login' is defined but never used           no-unused-vars
  Line 23:14:  'logout' is defined but never used          no-unused-vars

webpack compiled with 1 warning

CodePudding user response:

There are two problems here:

  1. Incorrect components usage in react
  2. Incorrect usage of Context API

You should use class component to use its methods like this.setState.

But you use this for functional component.

https://reactjs.org/docs/hooks-intro.html

https://reactjs.org/docs/components-and-props.html#function-and-class-components

https://reactjs.org/docs/context.html#contextprovider

P.S. If you want to transfer data to a child component, where it will be used - use props.

  • Related