React API returns empty - reactjs

fairly new to react but I have the following API data I want to create as a list or whatever:
https://jsonblob.com/53c7f296-d79d-11e8-839a-a312b719c60a
My react component looks like this:
class Contacts extends Component {
constructor(props) {
super(props)
this.state = {
contacts:[]
}
}
componentDidMount() {
fetch('https://api.billysbilling.com/v2/contacts?organizationId=kZeGqbBRSXyeeDoWNkF3jQ',{
headers: {
'X-Access-Token': API_KEY,
'Content-Type': 'application/json'
},
})
.then(response => {
return response.json();
})
.then(response => console.log(response))
.then(d => {
this.setState({ contacts: d });
console.log("state", this.state.contacts)
})
}
render() {
return (
<div>
{
this.state.contacts.map(((contact, index) =>
<th key={`${contact.contact}${index}`}>
<div>
<div>
{contact.contact}
</div>
</div>
</th>
))
}
</div>
);
}
But however it seems to return nothing.
The console.log actually shows the data, so I am pretty stuck.
It would be awesome if some of you could help.
The state also just returns an empty array in the react tools in chrome.

When you write then(response => console.log(response)), you are not returning anything, so d will be undefined in the function given to the following then.
You could write it like this instead:
fetch('https://api.billysbilling.com/v2/contacts?organizationId=kZeGqbBRSXyeeDoWNkF3jQ',{
headers: {
'X-Access-Token': API_KEY,
'Content-Type': 'application/json'
},
})
.then(response => {
return response.json();
})
.then(d => {
console.log(d);
this.setState({ contacts: d.contacts });
});

Related

API POST using fetch helper function doesn't render update after response is received

Beginner at React (and JS)...
I am trying to update text on the screen after my API helper function has completed a call. Instead, it returns empty. I have verified with the console that the data is being received. I followed the ComponentDidMount method from other similar questions but am still having no success. My code also seems to make multiple API calls, even though my intent is to only make one; I have to wonder if the issue stems from that.
Helper function:
export function apiHelper(url, data = {}, method = 'POST') {
return fetch(url, { // Return promise
method: method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
})
.then(res => res.json())
.then((result) => {
console.log(result);
return result;
}, (error) => {
error = error;
})
}
React Component that renders incorrectly after data is received:
class Headache extends React.Component {
constructor(props) {
super(props);
this.state = {
apiResponse: null,
};
}
componentDidMount() {
apiHelper(URLredacted,JSONredacted)
.then(response => {
this.setState({
apiResponse: response
});
console.log("state set.",response)
});
}
render() {
const jsonResponse = JSON.stringify(this.props.apiResponse)
return (
<div>
<img className="logoheader" src = {logo}/>
<ColoredLine color="grey"/>
<p>{jsonResponse}</p>
</div>
);
}
}
export function apiHelper(url, data = {}, method = 'POST') {
return fetch(url, { // Return promise
method: method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
})
.then(res => res.json())
.catch(err=>console.log(err))
}
second page:
class Headache extends React.Component {
constructor(props) {
super(props);
this.state = {
apiResponse: null,
};
}
componentDidMount() {
apiHelper(URLredacted,JSONredacted)
.then(response => {
this.setState({
apiResponse: response
});
console.log("state set.",response)
});
}
render() {
const jsonResponse = JSON.stringify(this.props.apiResponse)
return (
<div>
<img className="logoheader" src = {logo}/>
<ColoredLine color="grey"/>
<p>{jsonResponse && ""}</p>
</div>
);
}
}
if these code dont work you will be need asyn function because you need to wait to fetch data.

Can't Render Data with API Call

I've been stuck on this for quite some time now, I can't use a get request and have to use post as that is the only way I am able to get field values back. And no matter what I do, I can't get ANY data to render, as of right now, all i see is the loading... telling me that the data is null. yet I don't know how to change this. Any help would be appreciated.
this is using Fetch to call the QuickBase RESTful API to get multiple field values to just use as data points on line charts. I know this shouldn't be this hard, yet nothing I do can render any data. Using React as well.
import React, { Component } from 'react'
let headers = {
'QB-Realm-Hostname': 'XXXXXXXXXXX.quickbase.com',
'User-Agent': 'FileService_Integration_V2.1',
'Authorization': 'QB-USER-TOKEN XXXXXX_XXXXX_XXXXXXXXXXXXXXXX',
'Content-Type': 'application/json'
};
class JobsTableApi extends Component {
state = {
data: null,
}
componentDidMount() {
this.fetchData();
}
fetchData = () => {
let body = {"from":"bpz99ram7","select":[3,6,80,81,82,83,86,84,88,89,90,91,92,93,94,95,96,97,98,99,101,103,104,105,106,107,109,111,113,115,120,123,224,225,226,227,228,229,230,231,477,479,480,481],"sortBy":[{"fieldId":6,"order":"ASC"}],"groupBy":[{"fieldId":40,"grouping":"equal-values"}],"options":{"skip":0,"top":0,"compareWithAppLocalTime":false}}
fetch('https://api.quickbase.com/v1/records/query', {
method: 'POST',
headers: headers,
body: JSON.stringify(body)
}).then(res => res.json())
.then( res => {
this.setState({
data: [],
})
});
}
render() {
const { data } = this.state;
if (data === null) return 'Loading...';
return (
<div>
<h3>
{data}
</h3>
</div>
)
}
}
export default JobsTableApi;
some users have said to map through, but the problem is I don't know how with my current code. some say to use data.value yet it's an array. i've tried data[3], since there is no 'job name' field, or 'amount' field, it's all split up by number as shown above in my select body.
Thanks,
I guess the root cause is coming from using same names in the React's fetch and as a key in the QB response.
You can try to reach data by map via data["data"][item][6].value (6 is a field ID)
I have created and tested the following and it works properly.
<div id="mydiv"></div>
<script type="text/babel">
let headers = {
'QB-Realm-Hostname': 'XXXXXXXXXX.quickbase.com',
'User-Agent': 'FileService_Integration_V2.1',
'Authorization': 'QB-USER-TOKEN XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
'Content-Type': 'application/json'
};
class JobsTableApi extends React.Component {
constructor(props) {
super(props);
this.state = {
data: null,
};
}
componentDidMount() {
this.fetchData();
}
fetchData = () => {
let body = {"from":"XXXXXXXXXXX","select":[3,6,7],"sortBy":[{"fieldId":6,"order":"ASC"}],"groupBy":[{"fieldId":6,"grouping":"equal-values"}],"options":{"skip":0,"top":0,"compareWithAppLocalTime":false}}
fetch('https://api.quickbase.com/v1/records/query', {
method: 'POST',
headers: headers,
body: JSON.stringify(body)
}).then(response => response .json())
.then(data => this.setState({ data }));
}
render() {
const { data } = this.state;
if (data === null) return 'Loading...';
return (
<ul>
{Object.keys(data["data"]).map(item =>
<li key={item}>
<a> {data["data"][item][6].value} </a>
</li>
)}
</ul>
)
}
}
ReactDOM.render(<JobsTableApi />, document.getElementById('mydiv'))
</script>

Fetch Array data from API ReactJS

i try fetch array data from a API with token, the problem is i fail to render/bind to display,every time debug will show error message like this. Please guide me, im new to react, this is my 1st app.
how to bind array to myadapater?
error
here my code:
import React, { Component } from "react";
import ReactDOM from "react-dom";
const url = " "; //api customer
const token = " "; //token
class Client extends Component {
constructor(props) {
super(props);
this.state = {
error: undefined,
isLoaded: false,
items: []
};
this.getData = this.getData.bind(this);
}
componentDidMount() {
this.getData();
}
getData() {
return fetch(url, {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: "Bearer " + token
}
})
.then((res) => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
items: result
});
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
);
}
render() {
const { error, isLoaded, items } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div>
<p>data {items}</p>
{items.map((items) => (
<div>{items.name}</div>
))}
</div>
);
}
}
}
export default Client;
There is only one real issue.
The use of {items} in the render method. If you want to display the actual JSON try {JSON.stringify(items)} instead.
Besides that i would also not use the same name in the map. So instead of items for the map function i would use item since you are dealing with one of the items.
<div>
<p>data {JSON.stringify(items)}</p>
{items.map((item) => (
<div>{item.name}</div>
))}
</div>
Additionally, since you only use getData in the componentDidMount you do not need to bind it in the constructor (that is required if you intent to pass that function to other component/functions outside of the current one)
And you also do not need to return anything for the getData function since you handle the result in the then handlers.
So,
class Client extends Component {
constructor(props) {
super(props);
this.state = {
error: undefined,
isLoaded: false,
items: []
};
}
componentDidMount() {
this.getData();
}
getData() {
fetch(url, {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: "Bearer " + token
}
})
.then((res) => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
items: result
});
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
);
}
render() {
const { error, isLoaded, items } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div>
<p>data {JSON.stringify(items)}</p>
{items.map((item) => (
<div>{item.name}</div>
))}
</div>
);
}
}
}

React-Native: Display JSON Data

function getData(access_token) {
fetch('https://api.fitbit.com/1/user/-/activities/steps/date/today/1m.json', {
method: 'GET',
headers: {
Authorization: `Bearer ${access_token}`,
},
// body: `root=auto&path=${Math.random()}`
})
.then(res => res.json())
.then(res => {
console.log(`res: ${JSON.stringify(res)}`);
})
.catch(err => {
console.error('Error: ', err);
});
}
export default class App extends Component {
connectFitbit = () => {
OAuth(client_id, getData);
};
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>Welcome to Fitbit Integration</Text>
<Button title="connect fitbit" onPress={() => this.connectFitbit()} />
</View>
);
}
}
I'm trying to get fit bit steps JSON data in react native app ,
right now I am getting the output in console ,now i want to parse the step data in my app please help me out
If you want to display your data in to flatlist...
First you need to make array for saving your response data..
constructor(props) {
super(props);
this.state = {
...
result: [],
...
};
}
function getData(access_token) {
fetch('https://api.fitbit.com/1/user/-/activities/steps/date/today/1m.json', {
method: 'GET',
headers: {
Authorization: `Bearer ${access_token}`,
},
})
.then(res => res.json())
.then(res => {
console.log(`res: ${JSON.stringify(res)}`);
// if your response have anu json array
this.setState({
result:res.data,
});
})
.catch(err => {
console.error('Error: ', err);
});
}
After, in flatlist simply set this array,
<FlatList
data={this.state.result}
renderItem={item => your render view}
keyExtractor={(item, index) => your key item}/>

React: How do i trigger a function that contains a lifecycle method, from another component?

I have two components Navbar and Modal.
The Navbar contains a function called displayData() that contains a lifecycle method called componentDidMount().
So, In Modal Component I have a function that updates a data using FetchApi, On save of the data I need to trigger the displayData() function, I tried to pass it down as props, but it still doesn't get triggered
What am I doing wrong here? Any help would be appreciated
Navbar Code That contains the componentDidMount
//Displaying the Data
componentDidMount() {
this.displayData();
}
displayData() {
fetch("/user")
.then(data => data.json())
.then(data => {
console.log(data);
this.setState({
userArray: data
});
});
}
Modal Code where I need to trigger the displayData()
updateBtn = e => {
fetch(`/user/${id}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(newData)
})
.then(data => {
return data.json();
})
.then(data => {
console.log(data);
this.props.displayData(this); // This is where i'm trying to trigger the function
})
.catch(err => {
console.log(err);
});
};
Calling Modal from Navbar. I'm Passing displayData() in the display as props
<Modal
data={this.state.username}
dataone={this.state.email}
id={this.state.id}
close={this.closeModel}
log={this.logChange}
display={this.displayData}
/>
// Navbar Component
constructor(props) {
this.state = { isFetchComplete: false }
}
updateBtn = e => {
fetch(`/user/${id}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(newData)
})
.then(data => {
return data.json();
})
.then(data => {
this.setState({ isFetchComplete: true })
})
.catch(err => {
console.log(err);
});
};
{ this.state.isFetchComplete &&
<Modal
data={this.state.username}
dataone={this.state.email}
id={this.state.id}
close={this.closeModel}
log={this.logChange}
/>
}
// Modal Component
constructor (props) {
super(props)
this.state = {}
this.displayData = this.displayData.bind(this)
}
//Displaying the Data
componentDidMount() {
this.displayData();
}
displayData() {
fetch("/user")
.then(data => data.json())
.then(data => {
console.log(data);
this.setState({
userArray: data
});
});
}
Hope that helps!!
Define displayData() using arrow function so that it's lexically binded to Navbar:
displayData = () => {
fetch("/user")
.then(data => data.json())
.then(data => {
console.log(data);
this.setState({
userArray: data
});
});
}
And then in your Modal code, you call this.props.display since you passed down the prop through: display={this.displayData}
.then(data => {
console.log(data);
this.props.display();
})

Resources