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

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 })};
})
}))

Related

React JS get data from database using axios.get(url) with param

I'm trying to get data from a database using axios in React. Unfortunately for some reason the url I use doesn't return data although in the browser it does. The url contains a parameter, which is most likely a problem because when I use an url without a parameter, the data is returned.
constructor(props) {
super(props);
this.state = {
userId : this.props.match.params.userId,
users:[]
}
}
componentDidMount() {
const url = "http://localhost:8080/getUser?userId=1";
axios.get("http://localhost:8080/getUser", {params: {
userId: this.state.userId
}})
.then(response => response.data)
.then((data) => {
this.setState({users: data})
});
console.log(this.state.users);
}
Does anyone know how to get database data correctly using REST API and axios?
axios.get("http://localhost:8080/getUser", {
params: {
userId: this.state.userId
}
})
.then(response => response.json()) // You need to parse JSON
.then((data) => {
this.setState({users: data})
});
Only difference is in first .then, you need to parse data to JSON.

Updating object in react under componentDidMount

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 }));
}

State not updating correctly with get request from API

I am making two api GET requests, and with both I would like the state to update. For some reason it is only updating with the values from the first GET request.
I have tried using the spread operator to update the state and add in new values to current state (categories) from the GET requests.
axios // first get request
.get(
"LINK_TO_API"
)
.then(res => {
this.setState({
...this.state.categories,
categories: res.data.data
});
})
.catch(function(error) {
console.log(error);
});
axios // second get request
.get(
"LINK_TO_API"
)
.then(res => {
this.setState({
...this.state.categories,
categories: res.data.data
});
})
.catch(function(error) {
console.log(error);
});
I am currently getting 10 values from first GET request and would like to get the total of 20 values when I map through categories.
You will never get 20 values, due to are not appending values, you just are overwriting categories values in each call.
this.setState({
...this.state.categories,
categories: res.data.data
});
Here categories: res.data.data is being overwrited.
Just modify your code to:
axios
.get(
"LINK_TO_API"
)
.then(res => {
this.setState((state) => ({
...state,
categories: [...state.categories, ...res.data.data]
}));
})
.catch(function(error) {
console.log(error);
});
First of all, your spread operator is wrong, you have to wrap it into array categories: [...this.state.categories, ...res.data.data]. Also I advice you to wait all your post loaded and then set them to state:
Promise.all([axios.get('LINK_TO_API'), axios.get('LINK_TO_API_2')])
.then(allYourPosts => {
this.setState({ /* set it to state */ });
})
.catch((error) => {
console.log(error);
});
Assuming that categories is an array, you are overriding one array with another array.
In the code below, i am always returning a new array, and concating the new array with the previous array.
axios // first get request
.get('LINK_TO_API')
.then(res => {
this.setState({
categories: [...this.state.categories, ...res.data.data]
});
})
.catch(function(error) {
console.log(error);
});
axios // second get request
.get('LINK_TO_API')
.then(res => {
this.setState({
categories: [...this.state.categories, ...res.data.data]
});
})
.catch(function(error) {
console.log(error);
});

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()
}

Multiple get requests

I'm new with React and apis. I'm trying to make 2 get requests and assign 2 keys with their new values to "items" array. Here the "img" key coming from the second get request keeps overriding the whole object. So, it makes the first get request as if it doesn't exist. I need to just append the second key with the first key-values coming from the first fetch. Hope that does make sense.
fetch(url,{
method: 'GET'
})
.then((response)=> response.json())
.then((responseJson) => {
const newItems = responseJson.items.map(i => {
return{
name: i.name
};
})
const newState = Object.assign({}, this.state, {
items: newItems
});
console.log(newState);
this.setState(newState);
})
.catch((error) => {
console.log(error)
});
fetch(url2,{
method: 'GET'
})
.then((response)=> response.json())
.then((responseJson) => {
const newItems = responseJson.ebay.map(i => {
return{
img: i.picture.url[0]
};
})
const newState = Object.assign(this.state, {
items: newItems
});
console.log(newState);
this.setState(newState);
})
.catch((error) => {
console.log(error)
});
You can use this for the second request:
const newState = {
items: [...this.state.items, ...newItems]
}
this.setState(newState);

Resources