Boolean is not a function in react native fetch function - reactjs

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
}

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.

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

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

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

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