undefined-is-not-an-object-evaluating-this-state-datasource.map - javascript

componentDidMount(){
fetch('https://boboboi.online/c_api_sales/get_dest',{
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
port_code: 'CP-002',
api_key: 'ae9a6ce9a7479038d998060ef6d65ca9f86a13ed962a5366b3b0662cc52dde1b',
token: 'a959190d43520f8017ed2ca09ffc61bb'
}),
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson
}, function() {
// In this block you can do something with new state.
});
})
.catch((error) => {
console.error(error);
});
}
GetPickerSelectedItemValue=()=>{
Alert.alert(this.state.PickerValueHolder);
}

map() method can be used with array and not with object. So if you want to use map method you can try using it like Object.keys(this.state.dataSource).map((key, index)=> { //your function and logic });

Related

get the return value of an arrow function using React

I have this arrow function:
saveNewPermissions = (newGroupPermissions, groupName) => {
fetch(this.baseUrl + "/addPermission/group/" + groupName, {
method: 'PUT',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
},
body: JSON.stringify({
permissions: newGroupPermissions
})
}).then(response => response.json())
.then(json => {
console.log(JSON.stringify(json))
return json;
});
}
That function above is on the Service file, and on my component class i want to get the json that the function returns:
this.Service.save(newList, groupName)
I tried to do this but it didnt work:
this.uaaService.saveNewPermissions(newList, groupName).then(response=>{
console.log(response)
})
First of, you would want to return the Promise from the arrow function
saveNewPermissions = (newGroupPermissions, groupName) => {
return fetch(...) // returns a Promise object
}
then if you expect newList to be an array, you want to do:
this.uaaService.saveNewPermissions(newGroupPermissions, groupName).then((newListJSON) => {
this.Service.save(newListJSON, groupName);
})

Call REST API with auth token with React.js

This is a try of call a REST API that as an authentication token with React.js. I'm sending the token request as POST and it's been read as GET, can someone help me please?
componentDidMount() {
fetch("theURL/api-token-auth/", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
email: "EMAIL",
password: "PASSWORD"
}
})
.then(res => {
if (res.ok) {
return res.json();
} else {
throw Error(res.statusText);
}
})
.then(json => {
this.setState({
isLoaded: true,
token: json
});
})
.catch(error => console.error(error));
}
You are correctly using the method POST, so that's not an issue. However, the data you want to send should be in the body instead of in the headers.
componentDidMount() {
const email = "test#example.com";
const password = "foobar";
fetch("theURL/api-token-auth/", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
email,
password
})
})
.then(res => {
if (res.ok) {
return res.json();
} else {
throw Error(res.statusText);
}
})
.then(json => {
this.setState({
isLoaded: true,
token: json
});
})
.catch(error => console.error(error));
}

Using setState in fetch. Error: Warning: Can't call setState (or forceUpdate) on an unmounted component

Complete Error Here
fetch('http://localhost:3000/signin', {
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: this.state.emailInput,
password: this.state.passwordInput,
}),
})
.then(response => response.json())
.then((data) => {
if (data === 'Success!') {
this.setState({ route: '/' }, () => {
document.getElementById('sign-in-button').click();
signIn();
});
}
});
I'm 90% sure that the error occurs because I'm setState-ing when fetching from the server.
I'm using the 'route' state to dynamically set up my NavLink from React Router v4.
If your function in render method, it will give that error. Move your fetch function a lifecycle method.
componentDidMount(){
fetch('http://localhost:3000/signin', {
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: this.state.emailInput,
password: this.state.passwordInput,
}),
})
.then(response => response.json())
.then((data) => {
if (data === 'Success!') {
this.setState({ route: '/' }, () => {
document.getElementById('sign-in-button').click();
signIn();
});
}
});
}

fetch data error with react native

I used two classes
I call the second class as below
let s = new SearchExtend();
output = s.fetchData(search)
alert(output)
The second function:
fetchData = (search) => {
fetch('http://example.com/search.php' , {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
// Getting the search.
search: search
})
}).then((response) => response.json())
.then((responseJson) => {
return responseJson;
})
.catch((error) => {
console.error(error);
});
}
But i get in "alert" undefined
When I use this.setState instead of return, I get the following error:
warning setstate(...) can only update a mounted or mounting component
You are getting undefined because you are using promises. Initially it returns undefined and once promise is resolved you get the actually data.
A better way to handle this would be to return the promise and resolve it externally as follows:-
const fetchApi = () => {
return fetch("https://swapi.co/api/people" , {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
}).then((response) => {
return response.json();
})
.then((responseJson) => {
return responseJson;
})
.catch((error) => {
console.error(JSON.stringify(error));
});
}
fetchApi()
.then((data) => {
console.log("data", data);
})

ReactJS several fetch requests with promise

I need several fetch requests in my application to fetch data from different collections. Therefore, I wanted to use promises to make it work.
I have never used promises and despite my research on stackoverflow and other websites, I was not able to make it work.
Essentially, I need two fetch requests and I want to save the result of these requests to 2 different states.
This is what I have as of right now:
getFormData () {
fetch('/formdata', {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}})
.then(res => res.json())
}
getIcons () {
fetch('/icons', {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}})
.then(res => res.json())
}
getData () {
return Promise.all([this.getFormData(), this.getIcons()])
}
componentDidMount () {
this.getData()
.then(([formdata, icons]) => {
console.log(form + " " + icons);
})
.catch(err => console.log('There was an error:' + err))
}
But this did not work.
I also tried putting the promise in my componentDidMount() lifecycle method, like so:
componentDidMount () {
return Promise.all([this.getFormData(), this.getIcons()])
.then(([formdata, icons]) => {
console.log(formdata + " " + icons);
})
.catch(err => console.log('There was an error:' + err))
}
But this didn't work eiter.
I would like to save the data from /formdata to a state with the same name and the same goes for icons, but in the console it simply returns undefined undefined, instead of the formdata and the icons.
Where am I making a mistake in my code? How would I fix it?
You need to return Promise object from your methods. As of now you are not returning anything, so it's implicit undefined.
Try this:
getFormData () {
return fetch('/formdata', {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}})
.then(res => res.json())
}
getIcons () {
return fetch('/icons', {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}})
.then(res => res.json())
}
Just adding to #dfsq's answer, after returning the promises you can update the state within each function:
constructor(props) {
super(props);
this.state = {
formData = {},
icons: {}
}
}
getFormData () {
return fetch('/formdata', {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}})
.then(res => res.json(
this.setState({ formData: res.json })
))
}
getIcons () {
return fetch('/icons', {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}})
.then(res => res.json(
this.setState({ icons: res.json })
))
}

Categories

Resources