Home > Net >  React useState can't use from another component
React useState can't use from another component

Time:08-29

I Created a node.js server and i can write user info to MongoDb and i can create JWT in postman. so i want to use this on react project.

i created react router with private route which it's checking if there is an any user info in the local storage. example , (i did not create a axios post for login api. i just want to write user info with hardcode for see the code is working)

import { useAuth } from "../Context/AuthContext";
import { Navigate,useLocation } from "react-router-dom";

export default function PrivateRoutes({children}){

const user = JSON.parse(localStorage.getItem('user')) 

const location = useLocation();

if(!user){
    return <Navigate to="/login" state={{return_url:location.pathname}} />
}

return children;
}

authcontext

So , when i'm in a login page , i created a button and if i click this button i want to access to my AuthProvider and set user info to the LocalStorage in AuthProvider.

Login page, LoginPage.js

import { useAuth } from "../../../Context/AuthContext";
import { useNavigate,useLocation } from "react-router-dom";

export default function LoginPage(){

const navigate = useNavigate();
const location = useLocation();

const { setUser } = useAuth();

const loginHandle = () => {
    setUser({
        id : 1,
        username : 'umitcamurcuk'
    })
    
    navigate(location?.state?.return_url || '/');
}

const logoutHandle = () => {
    setUser(false);
    navigate('/');
}

return (
    <div>
        <button onClick={loginHandle}>Sign In</button>
        <button onClick={logoutHandle}>Cikis yap</button>
    </div>
   )
}

and my AuthContext page,

AuthContext.js

import { createContext, useState , useContext, useEffect } from "react";

const Context = createContext()

export const AuthProvider = ({ children }) => {

const [user , setUser] = useState(JSON.parse(localStorage.getItem('user')) || false);

const data = [ user, setUser ]

useEffect(() => {
    localStorage.setItem('user', JSON.stringify(user))
},[user])

return(
    <Context.Provider value={data}>
        {children}
    </Context.Provider>
)

}

export const useAuth = () => useContext(Context);

But when i click login button , this error show up error

LoginPage.js:12 Uncaught TypeError: setUser is not a function

and my indexJS

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import {BrowserRouter} from 'react-router-dom';
import { AuthProvider  } from './Context/AuthContext.js';
 
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <BrowserRouter>
    <AuthProvider>
      <App />
    </AuthProvider>
  </BrowserRouter>
);

is anyone for help me ?

Thanks

CodePudding user response:

You defined your value as array and not an object

const [user, setUser] = useAuth();

or

const data = { user, setUser }
  • Related