Reputation: 31
I'm Using React and nodejs I can successfully retrieve the data but I'm Unable to store it in a variable
OnSubmit(e){
const user={
email:this.state.email,
password:this.state.password,
}
axios.post('http://localhost:5000/Users/login',user)
.then(res=>(console.log(res.data)))//want to store this res.data in a variable
localStorage.setItem("token","got")
this.setState({
loggedin:true
})
Upvotes: 0
Views: 167
Reputation: 21
You can use this
axios.post('http://localhost:5000/Users/login',user)
.then(res=>{this.setState({userDetails: res.data})})
Upvotes: 1
Reputation: 492
Simply like this:
let userDetails = null;
axios.post('http://localhost:5000/Users/login',user)
.then(res=>{userDetails = res.data})
but if you want to use it outside the async call, then the value of userDetails will be null, as this is an Async fetch, so you can set this value in the state inside .then() like this
axios.post('http://localhost:5000/Users/login',user)
.then(res=>{this.setState({userDetails: res.data})})
Upvotes: 1
Reputation: 192
Define a variable in state, say "userData: null"; then do this,
axios.post('http://localhost:5000/Users/login',user)
.then(res=>{
// try to console.log `res` and checkout its hierarchy.
this.setState({userData: res.data});
})
Upvotes: 1
Reputation: 703
You can either same that to a variable or to your React state (class component) or to hooks. Multiple ways are available: class based component: axios.post('http://localhost:5000/Users/login',user) .then(res=>this.setState({data:res.data}))
Upvotes: 1
Reputation: 1473
In arrow function, Paranethesis ()
has implicit return statement and can contain only single statement. Whereas, brace {}
need explicit return statement and you can add multiple statements inside scope.
axios.post('http://localhost:5000/Users/login',user)
.then(res=> {
// Here, you can do required manipulation of data returned from promise
console.log(res.data)
localStorage.setItem("token","got")
this.setState({ loggedin:true })
})
Upvotes: 2