Undefined is not a function near setInterval - ecmascript-6

I am importing a function on onPressed but every time i press the icon it give me an error: 'undefined is not a function near setInterval'. please solve it.
onPressedButton = channelId =>
// fetch the value entered in the input field
//alert(channelId);
this.setState({channelId:channelId})
//fetch the value(channelId) that is enter in the input field
// make a request
var url = 'https://www.googleapis.com/youtube/v3/channels?key='+API_key+'&id=' + this.state.channelId + '&part=snippet,contentDetails,statistics';
this.setState({url: url});
fetch(url,{
method: 'GET'
})
.then((response) =>
response.json())
// fetchData(data);
alert('calling2');
})
//now fetching the response from the yt api again and again
.setInterval(() =>
{
var url = 'https://www.googleapis.com/youtube/v3/channels?key='+API_key+'&id=' + this.state.channelId + '&part=statistics';
fetch(url,{
method: 'GET'
})
.then((response) => updateSubscribers(response.json()))
},0)
.catch((error) => {
console.log(error);
});
}
The file from where i am importing this:
<Icon style = {styles.icon}
name = 'search'
type = 'material'
color= 'black'
onPress = {() => {
this.setState({channelId: this.getChannelId(this.state.term)});
obj.onPressedButton(this.state.channelId);
}
}
/>

You have a . before the setInterval that you need to remove.
//now fetching the response from the yt api again and again
setInterval(() =>
...

Related

How to print json api data in reactjs

I'm fetching json api details through GET request and trying to print it. Getting an error:
Error in the console is Uncaught ReferenceError: allUsers is not defined
const Dashboard = ({status, juser}) => {
const [allUsers, setAllUsers] = React.useState([]);
const id = juser.actable_id;
console.log(id); //getting id here as 1
const getAllusers = () => {
axios
.get(`http://localhost:3001/user/${id}`, { withCredentials: true })
.then((response) => {
console.log(response.data);
setAllUsers(response.data);
})
.catch((error) => {
console.log(" error", error);
});
};
React.useEffect(() => {
getAllusers();
}, []);
{allUsers.map((job_seeker, index) => {
return (
<div>
<p>{job_seeker.name}</p>
</div>
);
})}
}
export default Dashboard;
I'm new to react. Any help is appreciatable.
const [state, setState] = React.useState([]);
the state is where your data is located and setState is function to reset the state from anywhere,
so on your code,
const [jobseekers, allUsers] = React.useState([]); // change string to array
jobseekers is the variable where your data is located and allUsers is the function to store data into state.
set data to state using allUsers function,
const getAllusers = () => {
axios
.get(`http://localhost:3001/user/${id}`, { withCredentials: true })
.then((response) => {
allUsers(response.data);
})
.catch((error) => {
console.log(" error", error);
});
};
and map from jobseekers
{jobseekers.map((job_seeker, index) => {
return (
<div>
<p>{job_seeker.name}</p>
</div>
);
})}
Also I would suggest to rename your state and setState as,
const [allUsers, setAllUsers] = React.useState([]);
You didn't pass the value of response to allUsers, instead, you just created a new variable. So change
const allUsers = response.data;
to:
allUsers(response.data)
Besides, you can also improve the way that you have used useState. You have initialized it as an empty string while you'll probably store an array from response in jobseekers. So, initialize it as an empty array.
const [jobseekers, allUsers] = React.useState([]);

How to extract key and value from json in fetch method in React Native?

I'm new in React Native. I would like to extract a value from json with fetch to do a simple test to begin. But I don't understand, how to select a particular key from Json. Always, I have undefined return. I tried to modify my code with this post but it doesn't work. I tried to parse before but he didn't want because it's already an object.
This is my code:
checkLogin = () => {
const { name } = this.state;
const { surname } = this.state;
fetch('https://ffn.extranat.fr/webffn/_recherche.php?go=ind&idrch=' + name + '%20' + surname, {
method: 'GET',
}).then((response) => response.json())
.then((responseJson) => {
if (responseJson.ind == 'Individu non trouv\u00e9 !') {
alert("Id incorrect")
}
else {
alert("Id correct");
}
alert(JSON.stringify(responseJson.ind))
}).catch((error) => {
console.error(error);
});
}
This is my JSON format:
[{"iuf":"1366701","ind":"LEBRUN L\u00e9o (2000) H FRA - CN BEAUPREAU","sex":"#1e90ff","clb":"CN BEAUPREAU"}]
I know my request work because when I run this code alert(JSON.stringify(responseJson)).It return the entire json. So I don't know, how to resolve the undefined return.
Regards
Your json is an array, you either need to loop through it if there is multiple items inside, or just use responseJson[0] to read it. So if you want to read your json, your code would look like this :
const checkLogin = () => {
const { name } = this.state;
const { surname } = this.state;
fetch(
"https://ffn.extranat.fr/webffn/_recherche.php?go=ind&idrch=" +
name +
"%20" +
surname,
{
method: "GET"
}
)
.then(response => response.json())
.then(responseJson => {
// Since you have only one object inside your json, you can read the first item with 'responseJson[0]'.
if (responseJson[0].ind == "Individu non trouv\u00e9 !") {
alert("Id incorrect");
} else {
alert("Id correct");
}
alert(JSON.stringify(responseJson[0].ind));
// If you have multiple elements inside your responseJson,
// then here is a loop example :
// responseJson.forEach(item => {
// console.log('item ind = ', item.ind);
// });
})
.catch(error => {
console.error(error);
});
};
Use async await.
const checkLogin = async () => {
const { name } = this.state;
const { surname } = this.state;
const request = await fetch(
"https://ffn.extranat.fr/webffn/_recherche.php?go=ind&idrch=" +
name +
"%20" +
surname)
const response = await request.json();
console.log('result from server', response)
}

Why is this promise returning an [object Promise] and not the value?

I thought I fully understood promises, but I'm stumped on this. I realize I should use async/await, but for this example I specifically want to only use .then().
When I do this:
const theJson = fetch(
`https://s3-us-west-2.amazonaws.com/s.cdpn.io/28963/quotes.json`
)
.then( quoteTypeResponse => quoteTypeResponse.json() )
.then( data => {
console.log(data)
return data
});
the console.log(data) in the last function prints the JSON as expected, but when I try to console.log(theJson), the returned value, it prints [object Promise].. Why is this?
I was able to get the data outside of the function using react's useState/useEffect but not with just a vanilla global variable. I'm not trying to solve anything, but just want to understand why this does not work.
export default function App() {
let globalVar;
const [theQuote, setTheQuote] = useState({});
useEffect(() => {
fetch(`https://s3-us-west-2.amazonaws.com/s.cdpn.io/28963/quotes.json`)
.then(quoteTypeResponse => quoteTypeResponse.json())
.then(quoteType =>
fetch(
'https://programming-quotes-api.herokuapp.com/quotes/' +
quoteType.type
)
)
.then(quoteResponse => {
return quoteResponse.json();
})
.then(quote => {
setTheQuote({ quote: quote.en, author: quote.author });
globalVar = quote.author;
});
}, []);
return (
<div id="app">
<h1>{theQuote.quote}</h1> // renders
<h2>{theQuote.author}</h2> // renders
<h3>globalVar: {globalVar}</h3> // undefined
</div>
);
}
Because your second .then() is inside the first then(), so theJson is a Promise<T>. The nice thing about Promise<T> is that you can move an inner .then() call up a level and it will still work:
Change it from this:
const theJson = fetch(
`https://s3-us-west-2.amazonaws.com/s.cdpn.io/28963/quotes.json`
)
.then( quoteTypeResponse => quoteTypeResponse.json().then( data => {
console.log(data)
return data
} )
);
To this:
const theJson = fetch(
`https://s3-us-west-2.amazonaws.com/s.cdpn.io/28963/quotes.json`
)
.then( quoteTypeResponse => quoteTypeResponse.json() )
.then( data => {
console.log(data)
return data
});
But ideally, use async function so you can have this considerably simpler code instead:
const resp = await fetch( `https://s3-us-west-2.amazonaws.com/s.cdpn.io/28963/quotes.json` );
const data = await resp.json();
console.log( data );
#pushkin left a good link explaining the differences between async/await and using .then(), but basically, the value returned by the then() is only available within that block.
Promises cheat sheet: https://levelup.gitconnected.com/async-await-vs-promises-4fe98d11038f
fetch(`https://s3-us-west-2.amazonaws.com/s.cdpn.io/28963/quotes.json`)
.then(quoteTypeResponse => quoteTypeResponse.json())
.then(quoteType =>
fetch(
'https://programming-quotes-api.herokuapp.com/quotes/' + quoteType.type
)
)
.then(quoteResponse => {
return quoteResponse.json();
})
.then(quote => {
console.log(`q:${util.inspect(quote)}`);
document.getElementById('app').innerHTML = quote.en;
});

How do I return files as base-64 data URL strings from my API using MongoDB/GridFS?

I have a collection of Contacts inside my MongoDB
Those Contacts have avatars (or "profile pictures")
Here is the profile picture for the above user:
... and a chunk of that file (there's only one).
I'm trying to take ^^^ that ^^^ chunk and parse it into a base-64 data URL in order to return it from my server back to my application and use it inside an <img>'s src attribute.
app.get('/queryContacts', (req, res) => {
const getContacts = async query => {
let contacts = await db
.collection('contacts')
.find(query)
.toArray();
return contacts;
};
const getImages = async id => {
let imageUrl = 'data:image/jpg;base64';
await bucket
.openDownloadStream(new ObjectID(id))
.on('data', chunk => {
imageUrl += chunk.toString('base64');
})
.on('end', () => {
return imageUrl;
});
}
getContacts({account_id: new ObjectID(req.query.id)}).then(contacts => {
Object.keys(contacts).forEach(key => {
getImages(contacts[key].image_id).then(url => {
console.log(url); // undefined
contacts[key].imageUrl = url;
});
});
res.json(contacts);
});
});
The problem is that when I try this, the URL is undefined because getImages() isn't waiting for the 'end' event to finish.

get the all feeds data in single array in node.js

i have one doubt in the node js
i need to get the data from the rss feed
for that i install the rss-parser module in it
https://www.npmjs.com/package/rss-parser
let Parser = require('rss-parser');
let parser = new Parser();
(async () => {
let feed = await parser.parseURL('https://www.reddit.com/.rss');
console.log(feed.title);
feed.items.forEach(item => {
console.log(item.title + ':' + item.link)
});
})();
the code was like that
here they are using the async function
to get the data feed for one url
i have lot of urls
i need to loop it and get the feed details in single array
is there any posibility
please tell me is there any thing
i need to get the all feed url details in a single array
I tried as of now this
I tried this code
exports.getRssFeedLinks = () => {
// Setting URL and headers for request
// Return new promise
return new Promise((fulfill, reject) => {
// Do async job
let getSql = 'SELECT * FROM `news_feeds`';
//console.log(updateSql);
connection.query(getSql, (error, results, fileds) => {
if(error) {
reject(error);
}
else {
returnResult = JSON.stringify(results);
fulfill(returnResult);
}
});
})
}
exports.errHandler = function(err) {
console.log(err.message);
}
exports.getRssFeeds = (req, res) => {
let parser = new Parser();
let feedLink;
var dataPromise = this.getRssFeedLinks();
//console.log(dataPromise);
dataPromise.then(JSON.parse, this.errHandler)
.then(function(newFeeds) {
// Do one more async operation here
let feedsList = [];
if(newFeeds && newFeeds.length > 0) {
let feedLinks = [];
newFeeds.forEach(feed => {
feedLinks.push(feed.link);
});
(async () => {
let feeds = await Promise.all(feedLinks.map(parser.parseURL));
//feeds will have array of arrays, each array includes the response feed from each url
feeds = [].concat(...feeds) //if you want to flatten the array
feed.forEach(({item}) => {
console.log(item.title + ':' + item.link)
});
feeds.forEach(feed => {
console.log(feed.title);
feed.items.forEach(item => {
console.log(item.title + ':' + item.link)
});
})
})();
}
if(feedsList.length >0) {
res.send({
"success" : true,
"result" : feedsList
});
}
else {
res.send({
"success" : true,
"message" : "No Record ",
"result" : feedsList
});
}
}, this.errHandler);
}
Errors
(node:5700) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property
'options' of undefined
(node:5700) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
You can use Promise.all to send multiple request.
(async () => {
let feeds = await Promise.all(['https://www.reddit.com/.rss1', 'https://www.reddit.com/.rss2'].map(parser.parseURL));
//feeds will have array of arrays, each array includes the response feed from each url
feeds = [].concat(...feeds) //if you want to flatten the array
feed.forEach(({item}) => {
console.log(item.title + ':' + item.link)
});
//or use loop through each feed
feeds.forEach(feed => {
console.log(feed.title);
feed.items.forEach(item => {
console.log(item.title + ':' + item.link)
});
})
})();