S
S
szQocks2022-02-24 01:36:47
JavaScript
szQocks, 2022-02-24 01:36:47

How to properly set initialState in redux?

For example, in my initialState - there are a couple of fields, this is the user field - where user data is stored during authorization, and the auth field - a kind of additional flag - which becomes true if the user is authorized

const initialState = {
    auth: false,
    user: null
}


When the application starts, the fields are in the same form as I wrote above.
On the main page - there is a check for authorization and if the user is authorized, then an action is triggered in which the reducer changes the state, and this approach seems redundant to me because initially I have, for example, auth: false , then auth: true
And the question is - is it possible to at the stage of creating an object for the state - to check for auth ? and immediately assign the corresponding data to the fields?

For example:
const initialState = () => {
   let state = {}
     ....//проверка на auth
    ....//если авторизонван - то state.auth = true и state.user = response.user к примеру
return state;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexandroppolus, 2022-02-24
@Alexandroppolus

You can do this in the code where you create the initialState object. Where is it created?
Although the presence of authorization is unlikely to be checked synchronously. Even if there is a cookie or an entry in the localStorage, it is not a fact that it is valid, so you need to make a request.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question