problem with fetch in componentDidMount() - reactjs

my list of users is undefined when i try to console.log it.
Maybe i didn't get something ?
I'd like to get my list of users from my api who works (tested with postman) and put it into the console next i'd like to map my users to show it on the app
class Test extends Component {
constructor(props) {
super(props);
this.state = {
users: [],
}
}
componentDidMount() {
console.log("component did mount");
fetch("/user/list")
.then(res => {
return res.json();
})
.then(users =>
this.setState({users}, () =>
console.log("list of users => " + users)));
}
render() {
return (
<div className="form">
<ul>
{this.state.users.map((user) =>
<li key="user._id">{ user.name }</li>
)}
</ul>
</div>
);
}
} export default Test;
Thanks for help !

You are calling res.json() rather than returning res.json() from the first then on your fetch call
I've found this pattern to be helpful:
fetch(url)
.then(res => res.ok ? res.json() : Promise.reject())
As your code is now, users (the parameter in the second then would be undefined, because you are not returning anything from the first then

you have to return the res.json() to use it in the next .then()
.then(res => {
res.json();
})
should be
.then(res =>
res.json();
)
Or
.then(res => {
return res.json();
})
https://javascript.info/promise-chaining

You should be passing your res into res.json() and returning the results into your state.
componentDidMount() {
console.log("component did mount");
fetch("/user/list")
.then(res => res.json())
.then(users =>
this.setState(users,
() => {
console.log("list of users => " + users)
})
);
}

Michael Jasper response help me so much!
I found that fetch with GET method does not work if we pass any request body.
the full example is here
https://github.com/alexunjm/todo-list-react
const buildRequestOptions = ({
method = "GET",
raw = null, // I had my error here!, with GET raw need to be null
customHeaders = {name: 'value'},
}) => {
var myHeaders = buildHeaders(customHeaders);
var requestOptions = {
method,
headers: myHeaders,
body: raw,
redirect: "follow",
};
return requestOptions;
};
const listTasks = () => {
const url = `${uriBase}/task/sample`;
const requestOptions = buildRequestOptions({
customHeaders: { "Content-Type": "application/json" },
});
return fetch(url, requestOptions);
}
const asyncFn = ({
promiseToWait,
pendingFn,
successFn,
errorFn,
}) => {
return (dispatch) => {
dispatch(pendingFn());
promiseToWait
.then((res) => {
if (res.ok) {
return res.json();
}
// handled from server status 422 and 401
if (res.status === 422) {
// error message on body from server
return res.json();
}
if (res.status === 401) {
// custom error message hardcoded
return {errors: {action: 'no authorized'}}
}
console.log("http response no controlled", res);
return Promise.reject();
})
.then((body) => {
if (body.errors) {
const errors = Object.keys(body.errors).map(
(key) => key + " " + body.errors[key]
);
dispatch(errorFn(errors.join("; ")));
} else {
dispatch(successFn(body));
}
return body;
})
.catch((error) => {
console.log("error", error);
dispatch(errorFn("Unavailable server connection"));
});
};
};
const queryTasks = () => {
return asyncFn({
promiseToWait: listTasks(),
pendingFn: apiPending,
successFn: apiSuccessList,
errorFn: apiError,
});
}

Related

function is returning undefined while I am rexpecting some data

App.js
import { Component } from "react";
import "./App.css";
import checkUser from "./functions";
class App extends Component {
constructor() {
super();
console.log(checkUser('',''));
}
render() {
return (
<>
<h1 id="name">{this.user}</h1>
</>
);
}
}
export default App;
functions.js
let checkUser = (username, password) => {
let local_username = localStorage.getItem("username");
let local_token = localStorage.getItem("token");
let local_client_id = localStorage.getItem("client_id");
if (username === "" && password === "") {
fetch("/login?user=auth", {
method: "POST",
headers: {
username: local_username,
token: local_token,
client_id: local_client_id,
},
})
.then((data) => {
data.json();
})
.then((data) => {
return data
});
} else if (
username !== null &&
password !== null &&
local_client_id === null
) {
let res = fetch("/login?user=notloggedin", {
method: "POST",
headers: { username: username, password: password },
})
.then((res) => res.json())
.then((data) => {
if (data.status === true) {
localStorage.setItem("username", username);
localStorage.setItem("token", data.token);
localStorage.setItem("client_id", data.client_id);
return true;
} else {
return false;
}
});
}
};
export default checkUser;
I am expecting checkUser function to log user name but it is logging undefined.
It shows to request to server but not returning, I think that the problem is with the code in functions.js where I am returning something in a .then funtion.
In the first .then() you forget to return data.json(). you can either return:
.then((data) => {
return data.json();
})
//or wrap it in brackets so it automatically returns:
.then((data) => (
data.json();
))
//or make it one line:
.then((data) => data.json())

Fetch request is not updating the state

I have an react application connected to a database. Currently the app takes the database when it mounts and uses that to populate the state. The apps allows someone to post to the database. So far that works.
The issue is that I want the new posted content to be seen by the user. As it is the content only populates after I reload the page. I tried to repeat the coding in the componentDidMount() in a function that runs after the POST request, but for someone reason that is not working.
class App extends Component {
state = {
notes: [],
folders: [],
//noteID: 0,
//folderID: 0
};
componentDidMount() {
Promise.all([
fetch(`${config.API_ENDPOINT}/notes`),
fetch(`${config.API_ENDPOINT}/folders`)
])
.then(([notesRes, foldersRes]) => {
if (!notesRes.ok)
return notesRes.json().then(e => Promise.reject(e))
if (!foldersRes.ok)
return foldersRes.json().then(e => Promise.reject(e))
return Promise.all([
notesRes.json(),
foldersRes.json(),
])
})
.then(([notes, folders]) => {
this.setState({ notes, folders })
})
.catch(error => {
console.error({ error })
})
}
pageReload = () =>{
//console.log('pageReload ran');
Promise.all([
fetch(`${config.API_ENDPOINT}/notes`),
fetch(`${config.API_ENDPOINT}/folders`)
])
.then(([notesRes, foldersRes]) => {
if (!notesRes.ok)
return notesRes.json().then(e => Promise.reject(e))
if (!foldersRes.ok)
return foldersRes.json().then(e => Promise.reject(e))
return Promise.all([
notesRes.json(),
foldersRes.json(),
])
})
.then(([notes, folders]) => {
this.setState({ notes, folders })
})
.catch(error => {
console.error({ error })
})
}
folderSubmit = (f) => {
//console.log("folderSubmit ran " + f);
const newFolder = { "name" : f };
const postfolder = {
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(newFolder)
};
fetch(`${config.API_ENDPOINT}/folders`, postfolder).then(this.pageReload())
}
It looks like you are not setting your state after post. see below where you need to set your state.
folderSubmit = (f) => {
//console.log("folderSubmit ran " + f);
const newFolder = { "name" : f };
const postfolder = {
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(newFolder)
};
fetch(`${config.API_ENDPOINT}/folders`, postfolder)
.then(response => response.json())
.then(data => this.setState(data));
}

call function synchronously in reactjs

I want to call function only after previous function gets executed. I tried with promises but its not working,I also tried with async await but the last function is getting executed.After execution of first function its state value i want to pass to next function and so on.Please help me in this.Thanks in advance.
handleAllFunctionsOnClickPayLater() {
let promise = Promise.resolve();
promise
.then(() => this.handleGuestLogin())
.then(() => setTimeout(this.handleAddress(),1000))
.then(() => setTimeout(this.handlePayLater(),2000))
}
handleGuestLogin() {
const UserDetails = {
name: this.state.name,
email: this.state.email,
mobile: this.state.number
}
fetch(api,{
method : 'POST',
body: JSON.stringify(UserDetails)
})
.then(res => res.json())
.then(data => {
return this.setState({
cid: data.Data.cid
},() => {console.log(this.state.cid)})
})
}
handleAddress() {
var address_details = {
cid:this.state.cid
...other details
}
fetch(api,{
method : 'POST',
body: JSON.stringify(address_details)
})
.then(res => res.json())
.then(data => {
console.log("address added in db customer_address",data);
return this.setState({
address_id: data.address_id,
})
}
handlePayLater = () => {
var bookingDetails = {
cid: this.state.cid,
address_id: this.state.address_id
}
fetch(api,{
method : 'POST',
body : JSON.stringify(bookingDetails)
})
.then(res => res.json())
.then(data => {
return this.setState({bookingId:data.booking_id});
}
Assuming handleAddress, handleGuestLogin and handlePayLater return promises, you can use an async/await function
synchronousPromises = async () => {
try {
const handleGuestLoginResult = await this.handleGuestLogin();
const handleAddressResult = await this.handleAddress();
const handlePayLaterResult = await this.handlePayLater();
} catch (error)
{
return reject(error); //will cause .catch to fire
}
return resolve([
handleGuestLoginResult,
handleAddressResult,
handlePayLaterResult
]); //will cause .then to fire
}
since synchronousPromises is an async function, it itself returns a promise. to use it, you can call it as
callSyncronousPromises = () => {
synchronousPromises()
.then(success => {
//handle success
})
.catch(error => {
//handle error
}
}

Nested fetch/then methods

I am using the flickr API to search images and I would like to get photos with theirs tags at same time.
To do it, I need first to use flickr.photos.search method to fetch the photo_id and build the photo url (1st and 2nd 'then' methods). In the 3th 'then' part I used another API method flickr.photos.getInfo to get the tags for each photo and finally return urlPhoto and tagsInfo like json.
The problem is that tagsInfo variable continues been a promise and I can not render the tags (array) of the photo. However, urlPhoto has a correct value.
export function fetchAll(...) {
return fetch(BASE_URL + encodeGetParams(params1), options)
.then(response => {
return response.json();
})
.then((data) => {
return data.photos.photo.map(e =>
({
"photo_id": e.id,
"urlPhoto": 'https://farm'+e.farm+'.staticflickr.com/'+e.server+'/'+e.id+'_'+e.secret+'.jpg',
})
)
})
.then((data) => {
return data.map(e => {
const url = BASE_URL + encodeGetParams({ ...params2, "photo_id": e.photo_id });
const tagsInfo = fetch(url, options)
.then(data => data.json())
.then(data => data.photo.tags.tag.map(e => e._content));
return {
"urlPhoto": e.urlPhoto,
"tagsInfo": tagsInfo
}
}
)
})
}
You could create a separate promise for each element in the array, use Promise.all on those promises and return that.
export function fetchAll(/* ... */) {
return fetch(BASE_URL + encodeGetParams(params1), options)
.then(res => res.json())
.then(data => {
const promises = data.photos.photo.map(e => {
const result = {
urlPhoto: `https://farm${e.farm}.staticflickr.com/${e.server}/${e.id}_${e.secret}.jpg`
};
const url = BASE_URL + encodeGetParams({ ...params2, photo_id: e.photo_id });
return fetch(url, options)
.then(res => res.json())
.then(data => {
result.tagsInfo = data.photo.tags.tag.map(e => e._content);
return result;
});
});
return Promise.all(promises);
});
}
Do you not just need to return the last fetch and add an extra .then that would resolve to
{
"urlPhoto": e.urlPhoto,
"tagsInfo": tagsInfo
}
like
export function fetchAll(...) {
return fetch(BASE_URL + encodeGetParams(params1), options)
.then(response => {
return response.json();
})
.then((data) => {
return data.photos.photo.map(e =>
({
"photo_id": e.id,
"urlPhoto": 'https://farm'+e.farm+'.staticflickr.com/'+e.server+'/'+e.id+'_'+e.secret+'.jpg',
})
)
})
.then((data) => {
return data.map(e => {
const url = BASE_URL + encodeGetParams({ ...params2, "photo_id": e.photo_id });
return fetch(url, options)
.then(data => data.json())
.then(data => data.photo.tags.tag.map(e => e._content))
.then(tagInfo => {
return {
"urlPhoto": e.urlPhoto
"tagsInfo": tagsInfo
}
})
}
)
})
}
What you're currently doing is returning the urlPhoto/tagsInfo before the tagsInfo fetch promise has resolved so an extra then should fix it!

React Native - Undefined is not an object when evaluating promise

i am beginner react-native programmer . I am trying to return the responseJSON in a fetch function . I know it is asynchronous and will return promise, thus I need to use .then() , but when it says undefined is not an object.
here is the code
auth.js
export const onVerify = (email,password,navigation) => {
console.log('Verifying');
fetch('xxx',
{
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: 'email=' + email + '&password=' + password
})
.then((response) => response.json())
.then((responseJson) => {
if(responseJson.status == '200') {
Alert.alert(
'Login Successful',
'Welcome Home'
);
let data = {
name: responseJson.name,
id : responseJson.id
};
onSignIn();
return responseJson
}
in my signin.js
export default class SignIn extends React.Component{
step(){
onVerify(this.state.email,this.state.password,this.props.navigation).then(
function(data) {
console.log(data);
}
);
}
As said by #teivaz on the comment, your onVerify function returns nothing. Because the fetch call is asynchronous. So what you can do is return a Promise from onVerify then you'll be able to resolve it from step function.
This is how you can implement this,
export const onVerify = (email,password,navigation) => {
return new Promise((resolve, reject) => {
fetch('endpoint',
{
method,
headers,
body,
})
.then((response) => response.json())
.then((responseJson) => {
if(responseJson.status == '200') {
Alert.alert(
'Login Successful',
'Welcome Home'
);
let data = {
name: responseJson.name,
id : responseJson.id
};
onSignIn();
resolve(responseJson)
}
})
.catch(err => reject(err));
}
}
Also, make sure to catch the errors if any in step function.
export default class SignIn extends React.Component{
step(){
onVerify(this.state.email,this.state.password,this.props.navigation).then(
function(data) {
console.log(data);
}
)
.catch(err => console.log('Error occured', err));
}
}

Resources