React Native map "Undefined" is not a function - react-native

I'm trying to get data from API
but. I'm getting this error Error Image.
Here is my code.
const [datas, setDatas] = useState(" ");
const res = async () => {
const response = await axios.get("http://hasanadiguzel.com.tr/api/kurgetir");
setDatas(response.data.TCMB_AnlikKurBilgileri);
};
datas.map((item) => {
return (
<KurCard
title={item.Isim}
alis={item.BanknoteBuying}
satis={item.BanknoteSelling}
/>
);
});
How can I solve this?
I'm trying to map() datas, because I need it

Hi #n00b,
The data that datas is initially being set to an empty string, which does not have a map method. First, you need an empty array instead of an empty stringuseState([]). Now you can map.
const [datas, setDatas] = useState([]);
const res = async () => {
const response = await axios.get('http://hasanadiguzel.com.tr/api/kurgetir');
setDatas(response.data.TCMB_AnlikKurBilgileri);
};
{datas.length > 0 &&
datas.map((item) => {
return <KurCard title={item.Isim} alis={item.BanknoteBuying} satis={item.BanknoteSelling}/>
})
}
make sure you data. it has a length greater than 0 before trying to map over it.

Assuming your API request is valid, you would need to actually return something from the component itself and not just the array:
return datas.map((item) => {return <KurCard title={item.Isim} alis={item.BanknoteBuying} satis={item.BanknoteSelling}/>})

Related

for loop only iterating twice with axios

const [Datalist,setDatalist] = useState([]);
useEffect(() => {
axios.get( 'http://0.0.0.0:8000/api/v1/questions/history/1')
.then(response => {
const questions = response.data;
const datalist = [];
for (let i = 0; i < questions.length - 1; i++) {
const data = new Object();
data.isExpanded = false;
data.question_id = questions[i].id;
data.question = questions[i].content;
data.type = questions[i].type;
data.commentType = questions[i].comment_type;
data.answer = [];
datalist.push(data);
}
setDatalist(datalist);
});
},[]);
I have three questions in my database currently. The for loop should be iterating through 0 to 2, however, it is only iterating twice.
And I'm also having problems putting the data into Datalist.
Anybody know where the issue is??
Thanks in advance!!
Change your for loop to this:
for (let i = 0; i < questions.length; i++)
Since you are iterating over each question you receive, you could use the map-method (if your environment supports ES6-Syntax - but since you're using react, it most likely dooes).
From the MDN Docs:
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
With map, your code could look like this:
(Also note the removal of const data = new Object();. you can initialize an object and assign its properties/values at the same time)
const [Datalist,setDatalist] = useState([]);
useEffect(() => {
axios.get( 'http://0.0.0.0:8000/api/v1/questions/history/1')
.then(response => {
const questions = response.data;
const datalist = questions.map(question => {
return {
isExpanded: false;
question_id: question.id;
question: question.content;
type: question.type;
commentType: question.comment_type;
answer: [];
};
});
setDatalist(datalist);
});
},[]);

ProtocolError: Protocol error (Runtime.callFunctionOn): Target closed. - express.js and puppeteer-cluster

I want to iterate over key-pairs of data.extractRules and get elements data from the page.
This snippet inside forEach loop is causing app crashes. I tried hardcoding key and cssSelector and tried this outside of forEach loop and it worked.
const extractContent = {};
if (data.extractRules !== null) {
Object.entries(data.extractRules).forEach(async ([key, cssSelector]) => {
extractContent[key] = await page.$$eval(cssSelector, (elements) =>
elements.map((element) => element.outerHTML)
);
});
}
I figured out solution 😁
async function getSelectorContent(page, cssSelector) {
return page.$$eval(cssSelector, (elements) =>
elements.map((element) => element.outerHTML)
);
}
const extractContent = {};
if (data.extractRules !== null) {
await Object.entries(data.extractRules).reduce(
async (item, [key, cssSelector]) => {
await item;
extractContent[key] = await getSelectorContent(page, cssSelector);
},
Promise.resolve()
);
}

getting undefined on fetching rss feed

I want to randomly display some of the news from a google rss news feed using the url and the package react-native-url-preview. Im doing a fetch call on it:
const [rssFeed, setRssFeed] = useState([]);
const [shouldFetch, setShouldFetch] = useState(true);
var feed = [];
if (shouldFetch) {
console.log("shouldFetch");
getFeed();
setShouldFetch(false);
}
function getFeed() {
console.log("getFeed: " + shouldFetch);
fetch(
"https://news.google.com/rss/search?q=cars&hl=en-GB&gl=GB&ceid=GB%3Aen"
)
.then((response) => response.text())
.then((responseData) => rssParser.parse(responseData))
.then((rss) => {
console.log(typeof rss.items);
let feedItems = rss.items;
feed = feedItems;
// #ts-ignore
setRssFeed(rss.items);
});
}
if (!shouldFetch) {
console.log(rssFeed);
var randomArr = [];
while (randomArr.length < 4) {
var r = Math.floor(Math.random() * 100);
if (randomArr.indexOf(r) === -1) randomArr.push(r);
// #ts-ignore
console.log(r + " " + rssFeed[r].links[0].url);
}
}
This only works sometimes!
50% of the times I get the error: undefined is not an object (evaluating 'rssFeed[r].links'.
I thought this is beacause of the reloading in react-native and this is why i put the if check. But it has not solved it. Any ideas?
You can use optional chaining like rss?.items.
which means if rss is present check for rss.item.
rssFeed?.[r]?.links
Sometimes you get an Undefined Error because the UI gets rendered before the actual data is present.

How to count the number of elements in this particular object

I am making a call to an API and the response is somehow what I expect. However, I want to count the number of elements returned and I can not do it. This is what I think is important from the code.
Call in Vue component
data(){
return {
messages: {}
}
},
loadMessages(){
axios.get("api/messagesmenu")
.then((data) => { this.messages = data.data})
}
Api controller
public function index(){
$messages = Message::all()->where('read_at', NULL);
if(isset($messages)){
foreach($messages as $message){
$from = User::find($message->from_id);
$message->fromPrenom = $from->first_name;
$message->fromNom = $from->last_name;
$message->fromImage = $from->user_image;
}
}else{
$messages = [];
}
return $messages;
}
Type of response from the API
{"3":{"id":560,"from_id":2,"to_id":1,"content":"tgr","created_at":"2019-07-15 16:59:03","read_at":null,"fromPrenom":"abdel1","fromNom":"Hidalgo","fromImage":"user2-160x160.png"}}
I want to count the number of objects I obtain. if (in vue component) I do
this.messages.length
it returns undefined
Try this:
const messages = {"3":{"id":560,"from_id":2,"to_id":1,"content":"tgr","created_at":"2019-07-15 16:59:03","read_at":null,"fromPrenom":"abdel1","fromNom":"Hidalgo","fromImage":"user2-160x160.png"}}
console.log(Object.keys(messages).length) // 1
Or in your code:
...
.then((data) => {
this.messages = data.data
console.log(Object.keys(this.messages).length)
})

How to get data from Promise_ object?

I'm trying to get some data from a Promise_ object, in React Native app, in my AsyncStorage.
This is what I get in the console, in my Promise_ object :
Promise {_40: 0, _65: 0, _55: null, _72: null}
_40: 0
_55: {imageId: "1", imageName: "test.png"}
_65: 1
_72: null
__proto__: Object
So I don't know how to simply get the data in the _55 and show them in my code, I just want to take "1" and "test.png".
And sorry for my bad english. Thanks !
CODE :
This is the code for the set :
export const setBadgePicture = async (badgePictureId, badgePictureName) => await AsyncStorage.multiSet([['imageId', badgePictureId],['imageName', badgePictureName]])
and for the get :
export const getBadgePicture = async () => { await AsyncStorage.multiGet(['imageId', 'imageName']).then((response) => { tableResponse = { 'imageId' : response[0][1], 'imageName' : response[1][1], } }) return tableResponse }
you can do this to wait until your AsyncStorage returns the item.
AsyncStorage.getItem('YOUR_KEY').then((response)=>{
const itemVal = response;
})
AsyncStorage getItem function is an Asynchronous function. That means that if you want to get the return of that "get" function you will have to wait for the response. if you are using AsyncStorage.getItem() function add the reserved word await before the statement and in the function you are calling it put the reserved word async like this way:
async myFunctionWhereImCallingTheGetter () {
var myData = await AsyncStorage.getItem('theitemIamSearching');
}
Try then that:
export const getBadgePicture = async () => {
var response = await AsyncStorage.multiGet(['imageId', 'imageName']);
var tableResponse = { 'imageId' : response[0][1], 'imageName' : response[1][1], } });
return tableResponse;
}
What if you avoid multiGet?
export const getBadgePicture = async () => {
var imageId = await AsyncStorage.getItem('imageId');
var imageName = await AsyncStorage.getItem('imageName');
var tableResponse = { 'imageId' : imageId, 'imageName' : imageName };
return tableResponse;
}