First of all, please excuse me english, i am not a native speaker. I will try to explain my best.
I am trying to set the state of my component to a value received from http request that runs on componentDidMount(). After setState, i am passing props to my child components and expect them to rerender.
//App.js
import getAuthStateFromServer from './getAuthStateFromServer'
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
AuthState
}
this.getAuthState.bind(this)
}
componentDidMount() {
this.getAuthState()
}
getAuthState() {
getAuthStateFromServer().then(AuthState =>
this.setState({ AuthState })
)
}
render() {
return <h1>{this.state.AuthState.userData.userName}</h1>
}
}
//getAuthStateFromServer.js
import axios from 'axios'
import { getAuth } from './AuthStorage'
const getAuthStateFromServer = () => new Promise((resolve, reject) => {
// Create AuthState object
const AuthState = {
userData: {},
isLoggedIn: false,
}
// 1. get token
const { token } = getAuth()
// 2. if have token
if(token) {
// authenticate!
// send get request with token in header
axios.get('http://localhost:3500/validate', {
headers: { 'Authorization': `Bearer ${token}` }
}).then((res) => {
AuthState.userData = res.data
AuthState.isLoggedIn = true
resolve(AuthState)
}).catch(e => reject(e))
}
resolve(AuthState)
})
export default getAuthStateFromServer
So that got me the AuthState object when i console logged it but it did not rerender my component.
But if i take whats inside my getAuthFromServerFunction and put it in my componentDidMount like this..
componentDidMount() {
this.getAuthState()
}
getAuthState() {
const AuthState = {
userData: {},
isLoggedIn: false,
}
// 1. get token
const { token } = getAuth()
axios.get('http://localhost:3500/validate', {
headers: { 'Authorization': `Bearer ${token}` },
}).then((res) => {
AuthState.userData = res.data
AuthState.isLoggedIn = true
this.setState({ AuthState })
})
}
It Works.. and my component rerenders
I am completely stumped trying to figure this out.. Any help would be greatly appreciated, thank you