D
D
Damir Shaniyazov2022-04-13 08:48:38
React
Damir Shaniyazov, 2022-04-13 08:48:38

How to create an authentication?

Hello! Tell me how to do authentication?

I have this code. In the UseEffect hook , verifyAuthentication is called , which calls the server and checks whether there is such a token. If it is, then the user variable is not empty, and accordingly I display what I need.

But there is a problem, verifyAuthentication is delayed, which causes the Authentication component to be rendered . then I made a setAuth method that calls itself until the user variable appears (also not ideal). It seems to work, but there is a situation. First , the Authentication component is loaded , and thenDashboard , and it seems to be ok, but part of the js code is not loaded, for example, the button that should open the modal window will not work.

function App() {
    const {verifyAuthentication} = useActions()

    const [authStatus, setAuthStatus] = useState(false)

    useEffect(() => {
        if (localStorage.getItem('token')) {
            verifyAuthentication()
            setAuth(authStatus)
        }
    }, [])

    const setAuth = (bool: boolean) => {
        if (!bool) {
            let status = store.getState().auth.authResponse?.user ? true : false
            setTimeout(() => setAuth(status), 1000)
        }
        else {
            setAuthStatus(true)
        }
    }

    return authStatus ? <Dashboard/> : <Authentication/>
}

export default App;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Goretsky, 2022-04-14
@shaniyazovdamir

You're in a lot of trouble because you don't fully understand how the useEffect hook works. You have a verifyAuthentication() function - which contains requests, which means it is asynchronous. But you call it inside the useEffect hook without using its asynchronous features (await or .then()). Instead, you write crutches with setTimeout that work every other time.
Do you want to re-render the component with new data? You have as many as 3 ways to do this: pass new data to the prop, change the state, or use an array of dependencies in the useEffect hook - the choice is up to your needs.
Unfortunately, everything is not detailed in the docks for the react, and I didn’t come across any sensible explanations on other resources in Russian. Here are a couple of links in bourgeois by which you can understand howwork in useEffect with asynchronous code and how to use an array of dependencies in useEffect . Hope it helps you take it to the next level.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question