Updating object in react under componentDidMount - reactjs

I able to get the right data from my API node.js server. however when i try to setstate the object to render it it keeps returning null
i tried to use spread operator before the response but it still not working
import React, { Component } from "react";
import axios from "axios";
class Profile extends Component {
constructor(props) {
super(props);
this.state = {
UserData: null,
isLoading: false,
error: null
};
}
componentDidMount() {
this.setState({ isLoading: true });
axios
.get(
`http://localhost:5000/api/v1/profile/${this.props.match.params.platform}/${this.props.match.params.gamertag}`
)
.then(response => {
console.log(response.data);
})
.then(response => {
this.setState({
UserData: response.data,
isLoading: false
});
})
.catch(error => this.setState({ error, isLoading: false }));
}
render() {
const { isLoading, UserData } = this.state;
if (isLoading) {
return <p>Loading ...</p>;
}
console.log(UserData);
return <div>{UserData}</div>;
}
}
export default Profile;
when i try to log. the UserData log "null", but the "console.log(response.data)" works fine so it have to do something with the setState

when you chain data method like .then(), the following chained methods automatically receive value returned by the previous function.
getData
.then(res => console.log(res))
console.log itself will return nothing, thus the following .then() method will receive nothing.
getData
.then(res => console.log(res))
.then(data => console.log(data))
So if you do this, the second console.log() will log null.
You can fix it by returning something in your console.log step:
getData
.then(data => {
console.log(data);
return data;
})
.then(data => this.setState({ data: data }));
And the second console.log() will log properly.

You don't need two chain two then()'s, you can get the response and set the state after .then()
componentDidMount() {
this.setState({ isLoading: true });
axios
.get(
`http://localhost:5000/api/v1/profile/${this.props.match.params.platform}/${this.props.match.params.gamertag}`
)
.then(response => {
this.setState({
UserData: response.data,
isLoading: false
});
})
.catch(error => this.setState({ error, isLoading: false }));
}

Related

this.props.history.push('/') is getting executed even if there is an error

Even if there is an error in fetching data from firebase my router navigates to root component
axios.post('/orders.json', order)
.then(response => {
this.setState({ loading: false });
this.props.history.push('/');
})
.catch(err => {
//console.log(err)
this.setState({ loading: false });
});

Boolean is not a function in react native fetch function

Boolean is not a function react-native
When ever fetching API in react native from device its giving Boolean is not a Function
//Fetching a get api
fetch('http://dummy.restapiexample.com/api/v1/employees', {
method: 'GET'
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
})
.catch((error) => {
console.error(error);
});
variable declaration was wrong ,
this.state ={
isLoading:Boolean = true
}
////instead of that we should be
this.state ={
isLoading: true
}

How to save single object into state, from json end point axios

UPDATE:
axios
.get("https://cors-anywhere.herokuapp.com/" + "https://api.linkedin.com/v2/me", config)
.then(response => {
this.setState({profile: response.data})
})
^ saved the object in state for me :) Thanks everyone!!
I am a newbie to react. I am trying to save a single object from a JSON end point into the state of my react component. I am definitely returning the JSON data in the response. However it is not being saved into the state, can you see where I am going wrong?
// State needed for the component
constructor(props) {
super(props);
this.state = {
profile: {},
};
}
// Grabs profile data from the json url
private getProfile() {
let config = {
headers: {'Authorization':'Bearer AQVVEqNXTWV....'}
}
axios
.get("https://cors-anywhere.herokuapp.com/" + "https://api.linkedin.com/v2/me", config)
.then(response =>
response.data(profile => ({
id: `${ profile.id }`
}))
)
.then(profile => {
this.setState({
profile
});
})
// We can still use the `.catch()` method since axios is promise-based
.catch(error => this.setState({ error, isLoading: false }));
}
JOSN data returned:
{
"localizedLastName": "King",
"id": "fm0B3D6y3I",
"localizedFirstName": "Benn"
}
Your first then block looks wrong.
Try to do console.log there like this:
.then(response => {
console.log(response); // I am sure that you will get profile inside response.data or something similar
return response.data(profile => ({
id: `${ profile.id }`
}));
})
If you want to keep your first then that "prepares the data", then you should return a promise instead of data, like:
let config = {
headers: {'Authorization':'Bearer AQVVEqNXTWV....'}
}
axios
.get("https://cors-anywhere.herokuapp.com/" + "https://api.linkedin.com/v2/me", config)
.then(response => {
return new Promise((resolve, reject) => {
resolve( {
id: `${ response.data.id }`
});
});
}
)
.then(profile => {
this.setState({
profile
});
})
// We can still use the `.catch()` method since axios is promise-based
.catch(error => this.setState({ error, isLoading: false }));
Here's an example of how that would work:
I do believe that's a bit of an overkill though and you should be able to just set your state in the first then such as:
this.setState({profile: {id : response.data.id}});
Try to remove the second then, like this:
axios
.get("https://cors-anywhere.herokuapp.com/" + "https://api.linkedin.com/v2/me", config)
.then(response => {this.setState({ profile: response.data })};
})
}))

How to fix 'error 400 bad request' when making a post in react with axios?

I want to make a post request to add in database but I get 400 bad request error.
My express server is running on http://localhost:5000 and my react server on http://localhost:3000. The problem is that the post is on 3000 on the web instead of 5000.
The proxy is set on 5000. I have a get method also and that is running fine.
class Parts extends Component {
constructor(props) {
super(props);
this.addPartName = this.addPartName.bind(this);
this.addPartNumber = this.addPartNumber.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.state = {
parts: [],
partName: '',
partNumber: ''
};
}
addPartName(e) {
this.setState({
partName: e.target.value
})
}
addPartNumber(e) {
this.setState({
partNumber: e.target.value
})
}
onSubmit(e) {
e.preventDefault();
const part = {
partName: this.state.partName,
partNumber: this.state.partNumber
};
axios.post('/api/parts', part)
.then(res => console.log(res.data))
.catch(err => {
console.log(err);
})
this.setState({
partName: '',
partNumber: ''
})
}
componentDidMount() {
axios.get('/api/parts')
.then(res => {
const parts = res.data
this.setState({parts})
})
.catch(err => {
console.log(err);
})
}

Fetching methods depends on each other

I have been trying to fetch data from two sources in componentDidMount and second component's url relies on the data fetched from the first component, but it looks that state is not "updated" inside ComponenDidMount. I have tried to resolve it by using fetchDuel() in the constructor with no luck. Any suggestions? Thanks in advance!
class DuelDetail extends React.Component {
state = {
duel: [],
dataset: null
};
fetchDuel = () => {
const duelID = this.props.match.params.duelID;
axios.get(`http://127.0.0.1:8000/api/duel/${duelID}`,
{'headers': {'Authorization': `Token ${localStorage.getItem('token')}`}})
.then(res => {
this.setState({
duel: res.data
});
});
};
fetchDataset = () => {
axios.get(`http://127.0.0.1:8000/api/dataset/${this.state.duel.dataset}`,
{'headers': {'Authorization': `Token ${localStorage.getItem('token')}`}})
.then(res => {
this.setState({
dataset: res.data
});
});
};
componentDidMount() {
this.fetchDuel()
this.fetchDataset()
}
Just call the second function in the then() block of the first and pass the data as a param. setState is asynchronous so you can't rely on the data to be set immediately.
fetchDuel = () => {
const duelID = this.props.match.params.duelID;
axios.get(`http://127.0.0.1:8000/api/duel/${duelID}`,
{'headers': {'Authorization': `Token ${localStorage.getItem('token')}`}})
.then(res => {
this.setState({
duel: res.data
});
this.fetchDataset(res.data);
});
};
As the 2 actions are async you need to handle it accordingly.
Axios get returns a promise .So you can call the second action in the then block of the first action.
Also, setState is an aync action.(It gets queued up and doesn't get triggered instantly).
Use the data received from the first action, in its then block, pass it to the second action
Just call the second function in the .then() of the first function using data from the response. Example:
class DuelDetail extends React.Component {
state = {
duel: [],
dataset: null
};
fetchDuel = () => {
const duelID = this.props.match.params.duelID;
axios.get(`http://127.0.0.1:8000/api/duel/${duelID}`,
{'headers': {'Authorization': `Token ${localStorage.getItem('token')}`}})
.then(res => {
this.setState({
duel: res.data
});
this.fetchDataset(res.data.dataset)
// pass whatever property you get from the response here.
});
};
fetchDataset = (datasetId) => {
axios.get(`http://127.0.0.1:8000/api/dataset/${datasetId}`,
{'headers': {'Authorization': `Token ${localStorage.getItem('token')}`}})
.then(res => {
this.setState({
dataset: res.data
});
});
};
componentDidMount() {
this.fetchDuel()
}

Resources