API data won't convert to JSON format - javascript

Had the data in JSON in a previous build of my app but (with the help of StackOverflow community) redesigned how I call my API to fix various other breaking errors.
This is what I just tried. I log both the "regular" output and the attempt at converting it to JSON. The non-json output comes up as "{data: Array}" in my console while the JSON is undefined.
componentDidMount() {
axios
.get(
"API_KEY"
)
.then((res) => {
const data = res.data
const json = data.json
this.setState({ data, loading: false });
console.log(json);
console.log(data)
});
}
And here is my other attempt:
componentDidMount() {
axios.get("API_KEY").then((res) => {
const data = res.data;
this.setState({ data, loading: false });
console.log(data);
console.log(JSON.parse(JSON.stringify(data)));
});
}
All your help and advice is greatly appreciated! :)

I would suggest a better syntax using ES6.
const componentDidMount = async () => {
let { data } = await axios.get("API_KEY")
// Your data by default should be object or array.
// Regardless, both should worked fine.
console.log(data)
// In case it is just string and not undefined
if (data && typeof data !== 'object') {
data = JSON.parse(data)
}
this.setState({ data, loading: false })
}
Otherwise, try using breakpoint or console.log in the first place after getting the result. If the result is undefined, perhaps the promise is yet to resolve.

Related

Sort API Response without Storing the Data using JavaScript

I am using below code to call a GET API and then sort the Response with one of the object listed inside. I was told to convert the response to a ARRAY first then apply the sort function but it seems difficult and im missing some thing to sort the generated Array. Please help me, been trying for many days.
My Code:
url2 = "https://SampleAPI";
function fetchdata(){
fetch(url2)
.then(response=>{
return response.json();
})
.then(data=> {
console.log(data.data) // Getting the "Unsroted Response" Here
})
};
fetchdata(); //
const sortedResponse = ListModels.sort(function(a, b) { return parseInt(a.associateId) - parseInt(b.associateId) });
console.log("SORTED: ", sortedResponse) // Using to SORT THE RESPONSE WITH "associateId"
API Response for Above JS Code:
{
ListModels:(4) [
{
searchRank:0,
firstName:"Micheal",
lastName:"Brook",
associateId:"40",
payRateType:"Cost-only",
doctorStatus:null,
contractStartDate:"0001-01-01T00:00:00"
},
{
searchRank:0,
firstName:"Travis",
lastName:"Mayn",
associateId:"20",
payRateType:"Samp-only",
doctorStatus:null,
contractStartDate:"0001-01-01T00:00:00"
},
{
searchRank:0,
firstName:"Berry",
lastName:"Brooks",
associateId:"43",
payRateType:"Samp-only",
doctorStatus:null,
contractStartDate:"0001-01-01T00:00:00"
},
{
searchRank:0,
firstName:"Kim",
lastName:"Reed",
associateId:"25",
payRateType:"Samp-only",
doctorStatus:null,
contractStartDate:"0001-01-01T00:00:00"
}
],
totalRecord:4
}
I want to SORT above API response with "associateId" but with my Sorting line, im getting Error.
Please help me, i was told to hit the API Endpoint and sort without storing the response in CODE.
Error:
> error: Uncaught ReferenceError: ListModels is not defined
You have to move the sorting inside the response handler:
url2 = "https://SampleAPI";
function fetchdata(){
fetch(url2)
.then(response=>{
return response.json();
})
.then(data=> {
console.log(data.data) // Getting the "Unsroted Response" Here
const list = data.data;
const sortedResponse = list.sort(function(a, b) { return parseInt(a.associateId) - parseInt(b.associateId) });
console.log("SORTED: ", sortedResponse) // Using to SORT THE RESPONSE WITH "associateId" })
};
fetchdata(); //
The operations just after fetchdata are executed before the response comes from the server.

Response returning undefined react js axios

I trying to view status of a variable (salesforecasting) in database. Its responds by sending true or false which is received fine in Postman. However when it gets to react, it is shows undefined on console. if i see whole response object, there i can see value has return correctly but when i try to print it, it shows undefined.
in routes/api/salesforecasting.js
router.post('/view', function(req, res) {
const email="Hamzakhan003#gmail.com"
Customer.findOne({Email:email})
.then(data=>{
if(data){
let salevalue=data.Salesforecasting
res.send({
value: salevalue
});
}
});
});
in react file
componentDidMount(){
return axios.post('http://localhost:3000/api/sales-forecasting/view')
.then(response => {
//const output = response.value
const value = response.value;
{console.log(arr.value)}
this.setState({
added: value
});
});
}
I think u need to check in response.data.value instead of response.value.
axios populates the entire server response in response.data

Saving data from JSON end point

I am trying to map over the returned json and save the id into profile/profiles. However it does not seem to be mapping over the the data correctly, id: ${ profile.id } this bit needs to be changed? Any help is much appreciated.
Is their a online tool that can help with me this?
API request:
// Grabs company data from the json url
private getProfiles() {
let config = {
headers: {'Authorization':'Bearer AQVVEqNXTWVYPpPYivKNWVO8jsTx2eveV3kBg'}
}
axios
.get("https://cors-anywhere.herokuapp.com/" + "https://api.linkedin.com/v2/me", config)
.then(response =>
response.data.map(profile => ({
id: `${ profile.id }`
}))
)
.then(profiles => {
this.setState({
profiles
});
})
// We can still use the `.catch()` method since axios is promise-based
.catch(error => this.setState({ error, isLoading: false }));
}
Json data returned:
{
"localizedLastName": "King",
"id": "fm0B3D6y3I",
"localizedFirstName": "Benn"
}
When I console log the response.data
If the only data returned from your endpoint is the JSON you posted, then you don't have an array to map over.
You have a single object.
I've never used the axios library before, but looking at the source code response.data should be the JSON-parsed responseText from the XHR request:
https://github.com/axios/axios/blob/4f189ec80ce01a0275d87d24463ef12b16715d9b/lib/adapters/xhr.js#L51-L53
https://github.com/axios/axios/blob/4f189ec80ce01a0275d87d24463ef12b16715d9b/lib/defaults.js#L61
And now I see that you have posted response.data and it matches what I'd expect.
With that in mind I'd suggest handling it like this:
// Grabs company data from the json url
private getProfiles() {
let config = {
headers: {'Authorization':'Bearer AQVVEqNXTWVYPpPYivKNWVO8jsTx2eveV3kBg'}
}
axios
.get("https://cors-anywhere.herokuapp.com/" + "https://api.linkedin.com/v2/me", config)
.then(response => ({
id: profile.id
}))
.then(profiles => {
this.setState({
profiles
});
})
// We can still use the `.catch()` method since axios is promise-based
.catch(error => this.setState({ error, isLoading: false }));
}
What you're getting back is a single profile though. If you need profiles to be an array you'll need to put the response in an array.
I don't get it, what you are trying to do. In the map you have a callback function, but as I see you wrote there an object. If you are wanting to rewrite the current profile's id then write this:
response.data.map(profile => ({
profile.id = `${ profile.id }`;
}))
But if you want it to make a variable then this:
response.data.map(profile => ({
let id = `${ profile.id }`;
}))

Get request yields response with data in it, but when accessing .data specifically it yields undefined

Apologies if the terminology is not great, still new to fullstack.
Hello! I am trying to get all the users in my DB. The get() response is OK as the client is receiving the response (see image below)
The problem is that when I try to fetch the .data I get undefined.
Here's my Vue Component
import UserService from '#/services/UsersService.js'
export default {
data () {
return {
users: null
}
},
async mounted () {
// GET request for all users.
this.users = UserService.index().data
console.log('The response is OK', await UserService.index())
console.log('when trying to fetch the .data I am getting ', await this.users)
}
}
The index() function
import Api from '#/services/Api'
export default {
index () {
return Api().get('users')
}
}
Everything works fine, except that I get undefined data...
I think you forgot to fetch the data asynchronously?
async mounted () {
// GET request for all users.
- this.users = UserService.index().data
+ const res = await UserService.index()
+ this.users = res.data
console.log('The response is OK', await UserService.index())
console.log('when trying to fetch the .data I am getting ', await this.users)
}
You correctly use await syntax in the first console.log, which might explain why the data return correctly.

Why I need to stringify an array of objects, and parse after retrieve it, in React/Redux?

I'm not sure if this is the correct way to go, but it's working. I'm not sure either of this is a problem of React/Redux, or just javascript behaviour.
This is my REDUX Actions:
export const getDetectedPersonList = () => {
return (dispatch, getState) => {
fetch("http://localhost:8080/detectedPersonsListWS")
.then(function(response) {
if (response.status >= 400) {
throw new Error("Bad response from server");
}
return response.json();
})
.then(function(detections) {
var detected = [{"a":1},{"b":2},{"c":3},{"d":4}];
dispatch({
type : GET_DETECTED_PERSON_LIST,
payload : JSON.stringify(detected)
})
})
}
}
And in REACT's presentational component I have:
componentDidMount() {
this.props.getDetectedPersonList();
}
render() {
if (typeof this.props.detectedPersonListJson == 'string'){
console.log(this.props.detectedPersonListJson);
var json = JSON.parse(this.props.detectedPersonListJson);
console.log(json); //The array is perfect as created before (detected)
}
The detected array is obviously mock (in real world I expect a REST response), but ilustrates the question I think, it's not a problem of async action.
My biggest problem is that I'm validating props, before and I was expecting an array, but cannot send the array directly because I receive: [object object] and is interpreted as string by typeof, but it's not... And I get an error doing JSON.parse(detected), if I haven't done JSON.stringify(detected) before.
Makes any sense? Best practices to follow? Thanks so much.

Categories

Resources