V
V
Vladimir2020-02-24 13:33:05
JavaScript
Vladimir, 2020-02-24 13:33:05

How to get value instead of promise?

How to get value instead of promise? If I write then, React throws an error saying I'm not returning a component.

I am getting data here:

export default async function userState() {

    const response = await fetch('http://localhost:4000/isAuth', { method: 'POST' });
    const state = await response.json();

    return state

}


Here come via component:

export default function CreateForm({id, method, action, title, formType, userState}) {

    formType = formType === 1 ? 'authenticate' : formType === 2 ? 'registration' : null;

    userState = userState();

    console.log(userState);

    return !userState ? formType === 'authenticate' ?
        (
            <form action={action} method={method} className='form' id={id}>

                <div className="title">{title}</div>

                <CreateInput id='email' placeholder='E-mail' type='text' />
                <CreateInput id='password' placeholder='Password' type='password' />

                <CreateButton className='authentication-submit' text='Войти' buttonType={null} />

                <li className="form-link"><Link to="register">Регистрация</Link></li>

            </form>
        ) : formType === 'registration' ?
        (
            <form action={action} method={method} className='form' id={id}>

                <div className="title">{title}</div>

                <CreateInput id='name' placeholder='Имя' type='text' />
                <CreateInput id='email' placeholder='E-mail' type='text' />
                <CreateInput id='password' placeholder='Пароль' type='password' />
                <CreateInput id='current-password' placeholder='Повторите пароль' type='password' />

                <CreateButton className='register-submit' text='Регистрация' buttonType={null} />

                <li className="form-link"><Link to="/">Авторизация</Link></li>

            </form>
        ) : null : null

}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir, 2020-02-24
@HistoryART

This is something not very similar to your react. Have you read the documentation?
If you are writing a functional component, then read https://reactjs.org/docs/hooks-faq.html#how-can-i-...
https://reactjs.org/docs/thinking-in-react.html
In short, then
1) The request to the localhost:4000/isAuth api needs to be performed only once, during component mounting
2) Since fetch is an asynchronous function, the result cannot be obtained directly, you need to save it to the state
3) in return provide the ability to return the third state when the data has not yet been received.
4) Read the doc from cover to cover.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question