Update State component after fetch Redux
First, sorry for my english :)
I'm learning React and Redux. I just want to know why I can't update the state of one container with redux. The only way to fix this probleme is to write a set Time out function (because JS is asynchronous).
But I'm sure, that there is a better way to code what I want to do. If someone could help me please.
My fetch is running without any probleme.
Container FormAmdmin.js
import React, {Component} from 'react';
import {Container, Row, Col} from 'react-bootstrap';
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';
import {getFormAdmin} from '../Actions/PostFormAdmin';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import './FormAdmin.css'
const MapDispatchToProps = dispatch => {
return bindActionCreators({getFormAdmin}, dispatch)
}
const MapStateToProps = state => {
return {Auth : state.Auth}
}
class FormAdmin extends Component {
constructor(props) {
super(props);
this.state = {
email: '',
password: '',
isSuccess: false,
response : {}
};
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
componentWillReceiveProps(nextProps){
console.log(nextProps)
let response = nextProps.Auth.response
let isSuccess = nextProps.Auth.isSuccess
this.setState({
response,
isSuccess
})
this.onNaviguateAdmin()
}
// there 's no change to the state of my component
onNaviguateAdmin = () => {
console.log(this.state)
}
// It's working thanks to a setTimeOut Fonction
// onNaviguateAdmin = () => {
// setTimeout(() => {
// console.log('succes', this.state)
// }, 1000)
// }
handleChange(e){
this.setState({
[e.target.name] : e.target.value
})
}
handleSubmit(e){
e.preventDefault();
const body = {
email : this.state.email,
password : this.state.password
}
this.props.getFormAdmin(body)
}
render() {
console.log('state render', this.state) // The state in the render is OK
const { Auth } = this.props
let divResult = <div></div>
if (this.state.response.flash ==='ok') {
divResult = <div>Connexion réussie</div>
}
else if (this.state.response.flash ==='Not a yet a Success') {
divResult = <div>Identifiants ou mot de passe invalides</div>
}
return (
<div className="ContainerFormAdmin">
<Container fluid>
<h3>Administration du site</h3>
<Row>
<Col xs={12}>
<form onSubmit={this.handleSubmit}>
<h5>Connexion à l'Administration</h5>
<div>
<TextField
name="email"
id="email"
label="email"
margin="normal"
onChange={this.handleChange}
/>
</div>
<div>
<TextField
name ="password"
id="password"
label="password"
margin="normal"
onChange={this.handleChange}
/>
</div>
<Button
type="submit"
>Connexion</Button>
</form>
</Col>
</Row>
</Container>
<div>{divResult}</div>
</div>
);
}
}
export default connect(MapStateToProps, MapDispatchToProps)(FormAdmin);
I use MapDispatchToProps to get an action : the fetch. I would like to get the response in the state of my component. That's why I'm using "componentWillReceiveProps" to update my state. But It's not working.
AuthReducer.js
const initialState = {
error: null,
response: {},
isSuccess: false
}
const FormAdmin = (state = initialState, action) => {
console.log('je rentre dans auth reducers')
switch (action.type) {
case 'FORM_ADMIN_SUCCESS':
if (action.payload.json.flash === 'ok') {
return {
...state,
response: action.payload.json,
isSuccess: true
}
} else if
(action.payload.json.flash === 'Not a yet a Success'){
return {
...state,
response: action.payload.json,
isSuccess: false
}
}
break
case 'FORM_ADMIN_ERROR':
return {
...state,
error: true,
isSuccess: false
}
default:
return state;
}
}
export default FormAdmin
Action PostFormAdmin.js
export const postFormAdminSuccess = (json) => ({
type : 'FORM_ADMIN_SUCCESS',
payload : {json}
})
export const postFormAdminError = (error) => ({
type : 'FORM_ADMIN_ERROR',
payload : {error}
})
function handleError(response){
if (!response.ok){
throw Error(response.statusText)
}
return response
}
export function getFormAdmin(formAdmin){
return(dispatch) => {
return fetch('http://localhost:4000/admin', {
method : 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body : JSON.stringify(formAdmin)
})
.then(handleError)
.then(res => res.json())
.then(
res => {
dispatch(postFormAdminSuccess(res));
},
err => {
dispatch(postFormAdminError(err));
console.log('erreur de response', err)
}
)
}
}
I'm using redux Thunk.
Index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import 'bootstrap/dist/css/bootstrap.min.css';
import { Provider } from 'react-redux'
import { createStore, applyMiddleware } from 'redux'
import allReducers from './Reducers/Index';
import reduxThunk from 'redux-thunk';
const createStoreWithMiddleware = applyMiddleware(reduxThunk)(createStore);
const store = createStoreWithMiddleware(
allReducers
)
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>, document.getElementById('root'));
I really appréciate if someone can help. I know it's working with a setTimeout fonction, but I'm sure that there is another way to do it.
Thank's for all !
hollowspy
javascript reactjs asynchronous redux redux-thunk
add a comment |
First, sorry for my english :)
I'm learning React and Redux. I just want to know why I can't update the state of one container with redux. The only way to fix this probleme is to write a set Time out function (because JS is asynchronous).
But I'm sure, that there is a better way to code what I want to do. If someone could help me please.
My fetch is running without any probleme.
Container FormAmdmin.js
import React, {Component} from 'react';
import {Container, Row, Col} from 'react-bootstrap';
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';
import {getFormAdmin} from '../Actions/PostFormAdmin';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import './FormAdmin.css'
const MapDispatchToProps = dispatch => {
return bindActionCreators({getFormAdmin}, dispatch)
}
const MapStateToProps = state => {
return {Auth : state.Auth}
}
class FormAdmin extends Component {
constructor(props) {
super(props);
this.state = {
email: '',
password: '',
isSuccess: false,
response : {}
};
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
componentWillReceiveProps(nextProps){
console.log(nextProps)
let response = nextProps.Auth.response
let isSuccess = nextProps.Auth.isSuccess
this.setState({
response,
isSuccess
})
this.onNaviguateAdmin()
}
// there 's no change to the state of my component
onNaviguateAdmin = () => {
console.log(this.state)
}
// It's working thanks to a setTimeOut Fonction
// onNaviguateAdmin = () => {
// setTimeout(() => {
// console.log('succes', this.state)
// }, 1000)
// }
handleChange(e){
this.setState({
[e.target.name] : e.target.value
})
}
handleSubmit(e){
e.preventDefault();
const body = {
email : this.state.email,
password : this.state.password
}
this.props.getFormAdmin(body)
}
render() {
console.log('state render', this.state) // The state in the render is OK
const { Auth } = this.props
let divResult = <div></div>
if (this.state.response.flash ==='ok') {
divResult = <div>Connexion réussie</div>
}
else if (this.state.response.flash ==='Not a yet a Success') {
divResult = <div>Identifiants ou mot de passe invalides</div>
}
return (
<div className="ContainerFormAdmin">
<Container fluid>
<h3>Administration du site</h3>
<Row>
<Col xs={12}>
<form onSubmit={this.handleSubmit}>
<h5>Connexion à l'Administration</h5>
<div>
<TextField
name="email"
id="email"
label="email"
margin="normal"
onChange={this.handleChange}
/>
</div>
<div>
<TextField
name ="password"
id="password"
label="password"
margin="normal"
onChange={this.handleChange}
/>
</div>
<Button
type="submit"
>Connexion</Button>
</form>
</Col>
</Row>
</Container>
<div>{divResult}</div>
</div>
);
}
}
export default connect(MapStateToProps, MapDispatchToProps)(FormAdmin);
I use MapDispatchToProps to get an action : the fetch. I would like to get the response in the state of my component. That's why I'm using "componentWillReceiveProps" to update my state. But It's not working.
AuthReducer.js
const initialState = {
error: null,
response: {},
isSuccess: false
}
const FormAdmin = (state = initialState, action) => {
console.log('je rentre dans auth reducers')
switch (action.type) {
case 'FORM_ADMIN_SUCCESS':
if (action.payload.json.flash === 'ok') {
return {
...state,
response: action.payload.json,
isSuccess: true
}
} else if
(action.payload.json.flash === 'Not a yet a Success'){
return {
...state,
response: action.payload.json,
isSuccess: false
}
}
break
case 'FORM_ADMIN_ERROR':
return {
...state,
error: true,
isSuccess: false
}
default:
return state;
}
}
export default FormAdmin
Action PostFormAdmin.js
export const postFormAdminSuccess = (json) => ({
type : 'FORM_ADMIN_SUCCESS',
payload : {json}
})
export const postFormAdminError = (error) => ({
type : 'FORM_ADMIN_ERROR',
payload : {error}
})
function handleError(response){
if (!response.ok){
throw Error(response.statusText)
}
return response
}
export function getFormAdmin(formAdmin){
return(dispatch) => {
return fetch('http://localhost:4000/admin', {
method : 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body : JSON.stringify(formAdmin)
})
.then(handleError)
.then(res => res.json())
.then(
res => {
dispatch(postFormAdminSuccess(res));
},
err => {
dispatch(postFormAdminError(err));
console.log('erreur de response', err)
}
)
}
}
I'm using redux Thunk.
Index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import 'bootstrap/dist/css/bootstrap.min.css';
import { Provider } from 'react-redux'
import { createStore, applyMiddleware } from 'redux'
import allReducers from './Reducers/Index';
import reduxThunk from 'redux-thunk';
const createStoreWithMiddleware = applyMiddleware(reduxThunk)(createStore);
const store = createStoreWithMiddleware(
allReducers
)
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>, document.getElementById('root'));
I really appréciate if someone can help. I know it's working with a setTimeout fonction, but I'm sure that there is another way to do it.
Thank's for all !
hollowspy
javascript reactjs asynchronous redux redux-thunk
Hi hollowspy, and welcome to StackOverflow! in React,setState()
is asynchronous. In other words, when you callsetState()
the state doesn't actually update immediately. You're just scheduling the state update, and React will apply it whenever it wants to. So the state of your component probably hasn't been updated by the time you callthis.onNaviguateAdmin()
. Try @Ujin's answer below and also see here for more info on updating state: reactjs.org/docs/…
– ethan.roday
Nov 23 '18 at 16:13
I knew that React is asynchronous. That's why I used the setTimeout fonction. That's why I would like to write a better code. I'll test @Ujin's answer and I'll say you ! Thanks :)
– hollowspy
Nov 23 '18 at 16:25
Sure thing! Don't forget to accept and upvote his answer if it works!
– ethan.roday
Nov 23 '18 at 16:26
Yes i's working like @Ujin's solution ! Thanks both of you ! (and i'have vote to his answer)
– hollowspy
Nov 23 '18 at 16:32
add a comment |
First, sorry for my english :)
I'm learning React and Redux. I just want to know why I can't update the state of one container with redux. The only way to fix this probleme is to write a set Time out function (because JS is asynchronous).
But I'm sure, that there is a better way to code what I want to do. If someone could help me please.
My fetch is running without any probleme.
Container FormAmdmin.js
import React, {Component} from 'react';
import {Container, Row, Col} from 'react-bootstrap';
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';
import {getFormAdmin} from '../Actions/PostFormAdmin';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import './FormAdmin.css'
const MapDispatchToProps = dispatch => {
return bindActionCreators({getFormAdmin}, dispatch)
}
const MapStateToProps = state => {
return {Auth : state.Auth}
}
class FormAdmin extends Component {
constructor(props) {
super(props);
this.state = {
email: '',
password: '',
isSuccess: false,
response : {}
};
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
componentWillReceiveProps(nextProps){
console.log(nextProps)
let response = nextProps.Auth.response
let isSuccess = nextProps.Auth.isSuccess
this.setState({
response,
isSuccess
})
this.onNaviguateAdmin()
}
// there 's no change to the state of my component
onNaviguateAdmin = () => {
console.log(this.state)
}
// It's working thanks to a setTimeOut Fonction
// onNaviguateAdmin = () => {
// setTimeout(() => {
// console.log('succes', this.state)
// }, 1000)
// }
handleChange(e){
this.setState({
[e.target.name] : e.target.value
})
}
handleSubmit(e){
e.preventDefault();
const body = {
email : this.state.email,
password : this.state.password
}
this.props.getFormAdmin(body)
}
render() {
console.log('state render', this.state) // The state in the render is OK
const { Auth } = this.props
let divResult = <div></div>
if (this.state.response.flash ==='ok') {
divResult = <div>Connexion réussie</div>
}
else if (this.state.response.flash ==='Not a yet a Success') {
divResult = <div>Identifiants ou mot de passe invalides</div>
}
return (
<div className="ContainerFormAdmin">
<Container fluid>
<h3>Administration du site</h3>
<Row>
<Col xs={12}>
<form onSubmit={this.handleSubmit}>
<h5>Connexion à l'Administration</h5>
<div>
<TextField
name="email"
id="email"
label="email"
margin="normal"
onChange={this.handleChange}
/>
</div>
<div>
<TextField
name ="password"
id="password"
label="password"
margin="normal"
onChange={this.handleChange}
/>
</div>
<Button
type="submit"
>Connexion</Button>
</form>
</Col>
</Row>
</Container>
<div>{divResult}</div>
</div>
);
}
}
export default connect(MapStateToProps, MapDispatchToProps)(FormAdmin);
I use MapDispatchToProps to get an action : the fetch. I would like to get the response in the state of my component. That's why I'm using "componentWillReceiveProps" to update my state. But It's not working.
AuthReducer.js
const initialState = {
error: null,
response: {},
isSuccess: false
}
const FormAdmin = (state = initialState, action) => {
console.log('je rentre dans auth reducers')
switch (action.type) {
case 'FORM_ADMIN_SUCCESS':
if (action.payload.json.flash === 'ok') {
return {
...state,
response: action.payload.json,
isSuccess: true
}
} else if
(action.payload.json.flash === 'Not a yet a Success'){
return {
...state,
response: action.payload.json,
isSuccess: false
}
}
break
case 'FORM_ADMIN_ERROR':
return {
...state,
error: true,
isSuccess: false
}
default:
return state;
}
}
export default FormAdmin
Action PostFormAdmin.js
export const postFormAdminSuccess = (json) => ({
type : 'FORM_ADMIN_SUCCESS',
payload : {json}
})
export const postFormAdminError = (error) => ({
type : 'FORM_ADMIN_ERROR',
payload : {error}
})
function handleError(response){
if (!response.ok){
throw Error(response.statusText)
}
return response
}
export function getFormAdmin(formAdmin){
return(dispatch) => {
return fetch('http://localhost:4000/admin', {
method : 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body : JSON.stringify(formAdmin)
})
.then(handleError)
.then(res => res.json())
.then(
res => {
dispatch(postFormAdminSuccess(res));
},
err => {
dispatch(postFormAdminError(err));
console.log('erreur de response', err)
}
)
}
}
I'm using redux Thunk.
Index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import 'bootstrap/dist/css/bootstrap.min.css';
import { Provider } from 'react-redux'
import { createStore, applyMiddleware } from 'redux'
import allReducers from './Reducers/Index';
import reduxThunk from 'redux-thunk';
const createStoreWithMiddleware = applyMiddleware(reduxThunk)(createStore);
const store = createStoreWithMiddleware(
allReducers
)
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>, document.getElementById('root'));
I really appréciate if someone can help. I know it's working with a setTimeout fonction, but I'm sure that there is another way to do it.
Thank's for all !
hollowspy
javascript reactjs asynchronous redux redux-thunk
First, sorry for my english :)
I'm learning React and Redux. I just want to know why I can't update the state of one container with redux. The only way to fix this probleme is to write a set Time out function (because JS is asynchronous).
But I'm sure, that there is a better way to code what I want to do. If someone could help me please.
My fetch is running without any probleme.
Container FormAmdmin.js
import React, {Component} from 'react';
import {Container, Row, Col} from 'react-bootstrap';
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';
import {getFormAdmin} from '../Actions/PostFormAdmin';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import './FormAdmin.css'
const MapDispatchToProps = dispatch => {
return bindActionCreators({getFormAdmin}, dispatch)
}
const MapStateToProps = state => {
return {Auth : state.Auth}
}
class FormAdmin extends Component {
constructor(props) {
super(props);
this.state = {
email: '',
password: '',
isSuccess: false,
response : {}
};
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
componentWillReceiveProps(nextProps){
console.log(nextProps)
let response = nextProps.Auth.response
let isSuccess = nextProps.Auth.isSuccess
this.setState({
response,
isSuccess
})
this.onNaviguateAdmin()
}
// there 's no change to the state of my component
onNaviguateAdmin = () => {
console.log(this.state)
}
// It's working thanks to a setTimeOut Fonction
// onNaviguateAdmin = () => {
// setTimeout(() => {
// console.log('succes', this.state)
// }, 1000)
// }
handleChange(e){
this.setState({
[e.target.name] : e.target.value
})
}
handleSubmit(e){
e.preventDefault();
const body = {
email : this.state.email,
password : this.state.password
}
this.props.getFormAdmin(body)
}
render() {
console.log('state render', this.state) // The state in the render is OK
const { Auth } = this.props
let divResult = <div></div>
if (this.state.response.flash ==='ok') {
divResult = <div>Connexion réussie</div>
}
else if (this.state.response.flash ==='Not a yet a Success') {
divResult = <div>Identifiants ou mot de passe invalides</div>
}
return (
<div className="ContainerFormAdmin">
<Container fluid>
<h3>Administration du site</h3>
<Row>
<Col xs={12}>
<form onSubmit={this.handleSubmit}>
<h5>Connexion à l'Administration</h5>
<div>
<TextField
name="email"
id="email"
label="email"
margin="normal"
onChange={this.handleChange}
/>
</div>
<div>
<TextField
name ="password"
id="password"
label="password"
margin="normal"
onChange={this.handleChange}
/>
</div>
<Button
type="submit"
>Connexion</Button>
</form>
</Col>
</Row>
</Container>
<div>{divResult}</div>
</div>
);
}
}
export default connect(MapStateToProps, MapDispatchToProps)(FormAdmin);
I use MapDispatchToProps to get an action : the fetch. I would like to get the response in the state of my component. That's why I'm using "componentWillReceiveProps" to update my state. But It's not working.
AuthReducer.js
const initialState = {
error: null,
response: {},
isSuccess: false
}
const FormAdmin = (state = initialState, action) => {
console.log('je rentre dans auth reducers')
switch (action.type) {
case 'FORM_ADMIN_SUCCESS':
if (action.payload.json.flash === 'ok') {
return {
...state,
response: action.payload.json,
isSuccess: true
}
} else if
(action.payload.json.flash === 'Not a yet a Success'){
return {
...state,
response: action.payload.json,
isSuccess: false
}
}
break
case 'FORM_ADMIN_ERROR':
return {
...state,
error: true,
isSuccess: false
}
default:
return state;
}
}
export default FormAdmin
Action PostFormAdmin.js
export const postFormAdminSuccess = (json) => ({
type : 'FORM_ADMIN_SUCCESS',
payload : {json}
})
export const postFormAdminError = (error) => ({
type : 'FORM_ADMIN_ERROR',
payload : {error}
})
function handleError(response){
if (!response.ok){
throw Error(response.statusText)
}
return response
}
export function getFormAdmin(formAdmin){
return(dispatch) => {
return fetch('http://localhost:4000/admin', {
method : 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body : JSON.stringify(formAdmin)
})
.then(handleError)
.then(res => res.json())
.then(
res => {
dispatch(postFormAdminSuccess(res));
},
err => {
dispatch(postFormAdminError(err));
console.log('erreur de response', err)
}
)
}
}
I'm using redux Thunk.
Index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import 'bootstrap/dist/css/bootstrap.min.css';
import { Provider } from 'react-redux'
import { createStore, applyMiddleware } from 'redux'
import allReducers from './Reducers/Index';
import reduxThunk from 'redux-thunk';
const createStoreWithMiddleware = applyMiddleware(reduxThunk)(createStore);
const store = createStoreWithMiddleware(
allReducers
)
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>, document.getElementById('root'));
I really appréciate if someone can help. I know it's working with a setTimeout fonction, but I'm sure that there is another way to do it.
Thank's for all !
hollowspy
javascript reactjs asynchronous redux redux-thunk
javascript reactjs asynchronous redux redux-thunk
asked Nov 23 '18 at 15:56
hollowspyhollowspy
63
63
Hi hollowspy, and welcome to StackOverflow! in React,setState()
is asynchronous. In other words, when you callsetState()
the state doesn't actually update immediately. You're just scheduling the state update, and React will apply it whenever it wants to. So the state of your component probably hasn't been updated by the time you callthis.onNaviguateAdmin()
. Try @Ujin's answer below and also see here for more info on updating state: reactjs.org/docs/…
– ethan.roday
Nov 23 '18 at 16:13
I knew that React is asynchronous. That's why I used the setTimeout fonction. That's why I would like to write a better code. I'll test @Ujin's answer and I'll say you ! Thanks :)
– hollowspy
Nov 23 '18 at 16:25
Sure thing! Don't forget to accept and upvote his answer if it works!
– ethan.roday
Nov 23 '18 at 16:26
Yes i's working like @Ujin's solution ! Thanks both of you ! (and i'have vote to his answer)
– hollowspy
Nov 23 '18 at 16:32
add a comment |
Hi hollowspy, and welcome to StackOverflow! in React,setState()
is asynchronous. In other words, when you callsetState()
the state doesn't actually update immediately. You're just scheduling the state update, and React will apply it whenever it wants to. So the state of your component probably hasn't been updated by the time you callthis.onNaviguateAdmin()
. Try @Ujin's answer below and also see here for more info on updating state: reactjs.org/docs/…
– ethan.roday
Nov 23 '18 at 16:13
I knew that React is asynchronous. That's why I used the setTimeout fonction. That's why I would like to write a better code. I'll test @Ujin's answer and I'll say you ! Thanks :)
– hollowspy
Nov 23 '18 at 16:25
Sure thing! Don't forget to accept and upvote his answer if it works!
– ethan.roday
Nov 23 '18 at 16:26
Yes i's working like @Ujin's solution ! Thanks both of you ! (and i'have vote to his answer)
– hollowspy
Nov 23 '18 at 16:32
Hi hollowspy, and welcome to StackOverflow! in React,
setState()
is asynchronous. In other words, when you call setState()
the state doesn't actually update immediately. You're just scheduling the state update, and React will apply it whenever it wants to. So the state of your component probably hasn't been updated by the time you call this.onNaviguateAdmin()
. Try @Ujin's answer below and also see here for more info on updating state: reactjs.org/docs/…– ethan.roday
Nov 23 '18 at 16:13
Hi hollowspy, and welcome to StackOverflow! in React,
setState()
is asynchronous. In other words, when you call setState()
the state doesn't actually update immediately. You're just scheduling the state update, and React will apply it whenever it wants to. So the state of your component probably hasn't been updated by the time you call this.onNaviguateAdmin()
. Try @Ujin's answer below and also see here for more info on updating state: reactjs.org/docs/…– ethan.roday
Nov 23 '18 at 16:13
I knew that React is asynchronous. That's why I used the setTimeout fonction. That's why I would like to write a better code. I'll test @Ujin's answer and I'll say you ! Thanks :)
– hollowspy
Nov 23 '18 at 16:25
I knew that React is asynchronous. That's why I used the setTimeout fonction. That's why I would like to write a better code. I'll test @Ujin's answer and I'll say you ! Thanks :)
– hollowspy
Nov 23 '18 at 16:25
Sure thing! Don't forget to accept and upvote his answer if it works!
– ethan.roday
Nov 23 '18 at 16:26
Sure thing! Don't forget to accept and upvote his answer if it works!
– ethan.roday
Nov 23 '18 at 16:26
Yes i's working like @Ujin's solution ! Thanks both of you ! (and i'have vote to his answer)
– hollowspy
Nov 23 '18 at 16:32
Yes i's working like @Ujin's solution ! Thanks both of you ! (and i'have vote to his answer)
– hollowspy
Nov 23 '18 at 16:32
add a comment |
1 Answer
1
active
oldest
votes
Try to pass a callback to setState so that onNaviguateAdmin
is called after actual change to state:
this.setState({
response,
isSuccess
}, this.onNaviguateAdmin)
Note that componentWillReceiveProps
is deprecated and may be the cause of your problems. You should use componentDidUpdate
instead:
componentDidUpdate(prevProps){
console.log(prevProps, this.props)
if (this.props.Auth !== prevProps.Auth) {
let response = this.props.Auth.response
let isSuccess = this.props.Auth.isSuccess
this.setState({
response,
isSuccess
}, this.onNaviguateAdmin)
}
}
thank's, it's works !! If componentWillReceiveProps is now deprecated, I suppose I should use componentDidUpdate. Is that correct ?
– hollowspy
Nov 23 '18 at 16:29
@hollowspy the new 'componentWillReceiveProps' is 'static getDerivedStateFromProps(nextProps, prevState)'
– kivul
Nov 23 '18 at 16:36
@kivulgetDerivedStateFromProps
is not designed for performing side effects. And I guess thatonNaviguateAdmin
is meant to cause some side effects.
– UjinT34
Nov 23 '18 at 16:40
@Ujin, it's works !! Thx for you help :)
– hollowspy
Nov 23 '18 at 17:09
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53449686%2fupdate-state-component-after-fetch-redux%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
Try to pass a callback to setState so that onNaviguateAdmin
is called after actual change to state:
this.setState({
response,
isSuccess
}, this.onNaviguateAdmin)
Note that componentWillReceiveProps
is deprecated and may be the cause of your problems. You should use componentDidUpdate
instead:
componentDidUpdate(prevProps){
console.log(prevProps, this.props)
if (this.props.Auth !== prevProps.Auth) {
let response = this.props.Auth.response
let isSuccess = this.props.Auth.isSuccess
this.setState({
response,
isSuccess
}, this.onNaviguateAdmin)
}
}
thank's, it's works !! If componentWillReceiveProps is now deprecated, I suppose I should use componentDidUpdate. Is that correct ?
– hollowspy
Nov 23 '18 at 16:29
@hollowspy the new 'componentWillReceiveProps' is 'static getDerivedStateFromProps(nextProps, prevState)'
– kivul
Nov 23 '18 at 16:36
@kivulgetDerivedStateFromProps
is not designed for performing side effects. And I guess thatonNaviguateAdmin
is meant to cause some side effects.
– UjinT34
Nov 23 '18 at 16:40
@Ujin, it's works !! Thx for you help :)
– hollowspy
Nov 23 '18 at 17:09
add a comment |
Try to pass a callback to setState so that onNaviguateAdmin
is called after actual change to state:
this.setState({
response,
isSuccess
}, this.onNaviguateAdmin)
Note that componentWillReceiveProps
is deprecated and may be the cause of your problems. You should use componentDidUpdate
instead:
componentDidUpdate(prevProps){
console.log(prevProps, this.props)
if (this.props.Auth !== prevProps.Auth) {
let response = this.props.Auth.response
let isSuccess = this.props.Auth.isSuccess
this.setState({
response,
isSuccess
}, this.onNaviguateAdmin)
}
}
thank's, it's works !! If componentWillReceiveProps is now deprecated, I suppose I should use componentDidUpdate. Is that correct ?
– hollowspy
Nov 23 '18 at 16:29
@hollowspy the new 'componentWillReceiveProps' is 'static getDerivedStateFromProps(nextProps, prevState)'
– kivul
Nov 23 '18 at 16:36
@kivulgetDerivedStateFromProps
is not designed for performing side effects. And I guess thatonNaviguateAdmin
is meant to cause some side effects.
– UjinT34
Nov 23 '18 at 16:40
@Ujin, it's works !! Thx for you help :)
– hollowspy
Nov 23 '18 at 17:09
add a comment |
Try to pass a callback to setState so that onNaviguateAdmin
is called after actual change to state:
this.setState({
response,
isSuccess
}, this.onNaviguateAdmin)
Note that componentWillReceiveProps
is deprecated and may be the cause of your problems. You should use componentDidUpdate
instead:
componentDidUpdate(prevProps){
console.log(prevProps, this.props)
if (this.props.Auth !== prevProps.Auth) {
let response = this.props.Auth.response
let isSuccess = this.props.Auth.isSuccess
this.setState({
response,
isSuccess
}, this.onNaviguateAdmin)
}
}
Try to pass a callback to setState so that onNaviguateAdmin
is called after actual change to state:
this.setState({
response,
isSuccess
}, this.onNaviguateAdmin)
Note that componentWillReceiveProps
is deprecated and may be the cause of your problems. You should use componentDidUpdate
instead:
componentDidUpdate(prevProps){
console.log(prevProps, this.props)
if (this.props.Auth !== prevProps.Auth) {
let response = this.props.Auth.response
let isSuccess = this.props.Auth.isSuccess
this.setState({
response,
isSuccess
}, this.onNaviguateAdmin)
}
}
edited Nov 23 '18 at 16:44
answered Nov 23 '18 at 16:10
UjinT34UjinT34
65910
65910
thank's, it's works !! If componentWillReceiveProps is now deprecated, I suppose I should use componentDidUpdate. Is that correct ?
– hollowspy
Nov 23 '18 at 16:29
@hollowspy the new 'componentWillReceiveProps' is 'static getDerivedStateFromProps(nextProps, prevState)'
– kivul
Nov 23 '18 at 16:36
@kivulgetDerivedStateFromProps
is not designed for performing side effects. And I guess thatonNaviguateAdmin
is meant to cause some side effects.
– UjinT34
Nov 23 '18 at 16:40
@Ujin, it's works !! Thx for you help :)
– hollowspy
Nov 23 '18 at 17:09
add a comment |
thank's, it's works !! If componentWillReceiveProps is now deprecated, I suppose I should use componentDidUpdate. Is that correct ?
– hollowspy
Nov 23 '18 at 16:29
@hollowspy the new 'componentWillReceiveProps' is 'static getDerivedStateFromProps(nextProps, prevState)'
– kivul
Nov 23 '18 at 16:36
@kivulgetDerivedStateFromProps
is not designed for performing side effects. And I guess thatonNaviguateAdmin
is meant to cause some side effects.
– UjinT34
Nov 23 '18 at 16:40
@Ujin, it's works !! Thx for you help :)
– hollowspy
Nov 23 '18 at 17:09
thank's, it's works !! If componentWillReceiveProps is now deprecated, I suppose I should use componentDidUpdate. Is that correct ?
– hollowspy
Nov 23 '18 at 16:29
thank's, it's works !! If componentWillReceiveProps is now deprecated, I suppose I should use componentDidUpdate. Is that correct ?
– hollowspy
Nov 23 '18 at 16:29
@hollowspy the new 'componentWillReceiveProps' is 'static getDerivedStateFromProps(nextProps, prevState)'
– kivul
Nov 23 '18 at 16:36
@hollowspy the new 'componentWillReceiveProps' is 'static getDerivedStateFromProps(nextProps, prevState)'
– kivul
Nov 23 '18 at 16:36
@kivul
getDerivedStateFromProps
is not designed for performing side effects. And I guess that onNaviguateAdmin
is meant to cause some side effects.– UjinT34
Nov 23 '18 at 16:40
@kivul
getDerivedStateFromProps
is not designed for performing side effects. And I guess that onNaviguateAdmin
is meant to cause some side effects.– UjinT34
Nov 23 '18 at 16:40
@Ujin, it's works !! Thx for you help :)
– hollowspy
Nov 23 '18 at 17:09
@Ujin, it's works !! Thx for you help :)
– hollowspy
Nov 23 '18 at 17:09
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53449686%2fupdate-state-component-after-fetch-redux%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Hi hollowspy, and welcome to StackOverflow! in React,
setState()
is asynchronous. In other words, when you callsetState()
the state doesn't actually update immediately. You're just scheduling the state update, and React will apply it whenever it wants to. So the state of your component probably hasn't been updated by the time you callthis.onNaviguateAdmin()
. Try @Ujin's answer below and also see here for more info on updating state: reactjs.org/docs/…– ethan.roday
Nov 23 '18 at 16:13
I knew that React is asynchronous. That's why I used the setTimeout fonction. That's why I would like to write a better code. I'll test @Ujin's answer and I'll say you ! Thanks :)
– hollowspy
Nov 23 '18 at 16:25
Sure thing! Don't forget to accept and upvote his answer if it works!
– ethan.roday
Nov 23 '18 at 16:26
Yes i's working like @Ujin's solution ! Thanks both of you ! (and i'have vote to his answer)
– hollowspy
Nov 23 '18 at 16:32