Answer the question
In order to leave comments, you need to log in
React renders faster than Redux writes state?
So I have a SPA application with an authorization form. As soon as the visitor sends an authorization request, a JWT token is returned to him and the application is rendered again. As soon as I decided to attach a {profile} reducer to process user data, the magic began (for me).
Here is the reducer:
const initialState = {
fetching: false,
user: {
username: undefined,
email: undefined,
}
}
export default function profile(state=initialState, action) {
switch (action.type) {
case GET_USER[0]:
return {...state, fetching:true };
case GET_USER[1]:
return {...state, fetching:false, user: action.payload};
case GET_USER[2]:
return {...state, fetching:false};
default:
return state;
}
}
########## Вот тут экшен ########################
export const getProfile = (dispatch, token) => {
dispatch({type: GET_USER[0]});
axios.get('http://127.0.0.1:8000/api/v0/user-detail', {headers: {'Authorization': 'JWT ' + token}})
.then(function (response) {
if (response.status === 200) {
return response.data;
}
})
.then(function (data) {
dispatch({type: GET_USER[1], payload: data})
})
.catch(error => dispatch({type: GET_USER[2]}))
};
export function checkToken(token, refresh) {
return (dispatch) => {
dispatch({type: VERIFY_TOKEN[0]});
axios.post('http://127.0.0.1:8000/api/v0/api-token-verify/', {token: token})
.then(function (response) {
if (response.status === 200) {
dispatch({type: VERIFY_TOKEN[1], payload: {token, refresh}});
######################## ВОТ ТУТ ВЫЗЫВАЮ ЮЗЕРА ###################################
getProfile(dispatch, token);
##################################################################################
} else if (response.status === 401) {
const data = response.data;
console.log(data['detail']);
if (data["detail"] === "Token is invalid or expired") {
refreshToken(refresh)
}
}
})
.catch(error => {
refreshToken(dispatch, refresh);
dispatch({type: VERIFY_TOKEN[2]})
})
}
}
componentDidMount() {
const token = localStorage.getItem('token');
const refresh = localStorage.getItem('refresh');
this.props.LoginActions.checkToken(token, refresh);
}
############ Проверяю состояние запроса
<div className="auth-true">
{this.props.profile.fetching === false ?
<div className="fu-world">
{console.log(this.props.profile.fetching)}
<div className="username">{this.props.profile.user.username}</div>
</div>
:
undefined }
<div onClick={::this.onClickLogOut} className="logout">Log Out</div>
</div>
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question