Exporting a state from hook function to another component

Viewed 4485

I have a hook function/file in which i want to export a state called 'isAuth'. When I try to import this state in another file as import {isAuth} from '../AuthService/AuthRoute' i get an attempted import error. My plan is to set and get this state globally in my react application

This is how I want to export the state from the hook function/compenent:

export default function AuthRoute () {

  const [isAuth, setIsAuth] = useState(false);
  
  return {isAuth}

}

This is how I plan to import the state

import  {isAuth} from '../AuthRoute/AuthRoute'

function Login () {
 
  const [usernameAuth, setUsernameAuth] = useState("");
  const [passwordAuth, setPasswordAuth] = useState("");
  const [loginStatus, setLoginStatus] = isAuth();  //Imported state
  const [inputResponse, setInputResponse] = useState("");
2 Answers

This is not how export works.

In your code, you're exporting the function itself, not the value it returns.

If you're going to write a custom hook, just use it like:

export default function useAuthRoute () {

  const [isAuth, setIsAuth] = useState(false);
  
  return {isAuth}

}
import useAuthRoute from '../AuthRoute/AuthRoute'

function Login () {
  const { isAuth } = useAuthRoute()
  ...

You need to "call" that function and use the returned value. And make sure you start the function's name with "use" so you follow React's hooks' rules. You can find more about export here

You can use contexts to set global states like this. Create a file called "AuthContext" that looks like this

import { createContext } from 'react';

export const AuthContext = createContext(false);

In your App.js file you can create a state and provide it to your child components like so

import React, { useState } from 'react';
import { AuthContext } from './path/to/AuthContext';


const App = props => {
const [isAuth, setIsAuth] = useState(false);

return (
<AuthContext.Provider value={[isAuth, setIsAuth]}>
//YOUR APPLICATION
</AuthContext.Provider >
)
}

Now you have your isAuth state provided to all of your top level components. If you ever want to view or manipulate that state in component simply do as follows:

import React, { useContext } from 'react';
import { AuthContext } from './path/to/AuthContext';

const YourComponent = props => {
const [isAuth, setIsAuth] = useContext(AuthContext);

return (
//Your component code
)
}

As a final note, I would advise against using a boolean for checking if someone is authorized or not on a global scale. It can cause weird problems on occasion. Much safer using strings like "AUTHORIZED" or "NOT_AUTHORIZED".

Related