Home > Mobile >  React useNavigate is erroring as not a function
React useNavigate is erroring as not a function

Time:05-31

So in previous React version I was able to use Redirect to change from one page to another when using some condition on if it would change. But with v6 redirect is no longer usable.

import React, {useState, Redirect, useNavigate} from 'react';
import './App.css';
import {Link} from 'react-router-dom'

function Main() {
    const handleLogInUsernameChange = (event) => {
        setLogInUsername(event.target.value)
    }

    const handleLogInPasswordChange = (event) => {
        setLogInPassword(event.target.value)
    }

    let navigate = useNavigate();
    
    function RedirectTo(){
        navigate('/dashboard')
    }

    function checkLogInCred(){
        fetch("https://api.apispreadsheets.com/data/xxxxxxxxxxxxxxxxxxx/").then(res=>{
            if (res.status === 200){
                // SUCCESS
                res.json().then(data=>{
                    const yourData = data
                    for(var a = 0; a < yourData.data.length - 1;a  ){
                        if(yourData.data[a].Password === logInPassword &&
                            yourData.data[a].UserName === logInUsername)
                            {
                                logInStatus = "Logged"
                                console.log("You have logged in")
                                a = yourData.data.length
                                //<Redirect to="/dashboard" />
                                RedirectTo()
                            }
                    }
                }).catch(err => console.log(err))
            }
            else{
                // ERROR
            }
        })
        //navigate('/dashboard')
    }

    return (
        <div>
            <p>
                <input type="text" placeholder="Enter username" onChange={handleLogInUsernameChange}></input>
            </p>
            <p>
                <input type="text" placeholder="Enter password" onChange={handleLogInPasswordChange}></input>
            </p>
            <p>
                <button onClick={checkLogInCred}>Login</button> 
            </p>
        </div>
    );
}

export default Main;

Seems like everything is only working in onClick functions only

CodePudding user response:

import {useNavigate} from "react-router-dom";

useNavigate is part of react-router-dom not React.

In your case, it will be something like:

import {Link,useNavigate} from 'react-router-dom'

CodePudding user response:

useNavigate is imported from react-router-dom, so in your case:

import {Link,useNavigate} from 'react-router-dom';

CodePudding user response:

you are importing it from then react.

import React, {useState, Redirect, useNavigate} from 'react';

import it from react-router-dom

import { useNavigate } from "react-router-dom";

hope it will resolve the redirection.

  • Related