React Native flatlist specific data - json

Im requiring data from a local json file just for test purposes (On a ideal world im going to fetch data from a remote url) this json file is an array with 8 objects, but I need the flatlist just to render the first 3, how can I do that?
My code:
import extratoData from "./extratoData.json"
export default function Body () {
const [data, setData] = useState([])
useEffect(() => {setData(extratoData)}, [])
return(
<FlatList
data={extratoData}
renderItem={({item}) => <ExtratoRenderItem title={item.title} amount={item.amount} date={item.date} time={item.time} cashback={item.cashBack}/>}
keyExtractor={(item, index) => index.toString()}
/>
)

You can just use the Array.prototype.slice() method.
var firstThree = extratoData.slice(0, 3);

Related

Access nested data api objects in react native

I need to access the data inside the object "priceRange" inside this api data structure 'https://api.chvcfcz6km-enapsysbu1-s1-public.model-t.cc.commerce.ondemand.com/geawebservice/v2/marketplace/products/search' but I haven't found the way to do it, I'm doing an axios call in react native as I show below:
export const RecommendationsView: React.FC = () => {
const [fetching, setFetching] = React.useState(true)
const navigation = useNavigation<NavigationProps>()
const [loading, setLoading] = useState(false)
const [items, setItems] = useState<any[]>([])
const getData = async () => {
const res = await axios.get(
'https://api.chvcfcz6km-enapsysbu1-s1-public.model-t.cc.commerce.ondemand.com/geawebservice/v2/marketplace/products/search'
)
console.log(res.data)
setItems(res.data.products)
setLoading(true)
setFetching(false)
//este setloading me habia funcionado la idea es reemplazarlo por el setfetching
}
React.useEffect(() => {
getData()
}, [])
return (
<View>
<View sx={Styles.header} />
{items?.map((item, index) => {
return (
<View key={index}>
<Text>{`${item?.name} + ${item?.priceRange}`}</Text>
</View>
)
})}
</View>
)
}
the call {item?.name} returns me correctly the items name, but if I do something like {item?.priceRange} or any of the data inside priceRange, it only returns [object Object] or undefined.
Your API return XML Response not JSON Response, you have to convert it to a json to make it work correctly.

How to loop through a JSON array with useEffect in React?

I am trying to loop through a JSON array with useEffect. When I use the below code (with the array removed from useState) with a single user specified, I am able to get the data. However it does not work with the entire array...any suggestions would be appreciated.
function GitHubUser() {
const [data, setData] = useState([]);
useEffect(() => {
fetch(`https://api.github.com/users/`)
.then(res => res.json())
.then(setData)
.catch(console.error);
}, []);
if (data) {
return (
<div>
<h1>{data.userId}</h1>
<img src={data.avatar_url} width={100} alt={"github avatar"}/>
<p>{data.login}</p>
</div>
);
}
return null;
}
It doen't work because when you do if (data) it returns true because empty array is true
const data = [];
if (data) {
console.log("Empty array is true");
} else {
console.log("Empty array is false");
}
So... when you try to get userId from an empty array it throws an error.
If data is supposed to be an array...
function GitHubUser() {
const [data, setData] = useState([]);
useEffect(() => {
fetch("https://api.github.com/users")
.then((res) => res.json())
.then(setData)
.catch(console.error);
}, []);
if (data) {
return (
<React.Fragment>
{data.map((user) => (
<div>
<h1>{user.userId}</h1>
<img src={user.avatar_url} width={100} alt={"github avatar"} />
<p>{user.login}</p>
</div>
))}
</React.Fragment>
);
}
return null;
}
You have to map each user to the expected output component. Using a map will prevent the previous behaviour because if no elements are present in the array, it will not map anything and return an empty component instead of an error.
If data is not supposed to be an array, then you shouldn't use a map nor initialize the state with an empty array because before running the fetch it will try to render the component and fail.
Is this something like you u want?
I removed the backslash after https://api.github.com/users*here*.
I set the data in useEffect hooks, in your example you didnt do it.
And mapped the array in data, it shows all the github users with
images and names.
.
function GitHubUser() {
const [data, setData] = useState([]);
useEffect(() => {
fetch(`https://api.github.com/users`) // removed the backslash here
.then(res => res.json())
.then(data => setData(data)) // changed this line
.catch(console.error);
}, []);
console.log(data)
return (
<div>
{data.map((item, key) => <> // Mapping through the array here
<h1 key={key}>{item.id}</h1>
<img src={item.avatar_url} width={100} alt={"github avatar"}/>
<p>{item.login}</p>
</>
)}
</div>
);
}

FlatList receiving undefined values after fetching json

I need to render a FlatList after fetching a json containing connections. The following piece of code runs correctly but the travel object inside the renderItem is always undefined.
import {Text, View, FlatList, ActivityIndicator} from 'react-native';
import React, {useEffect, useState} from 'react';
/**
* http://transport.opendata.ch/v1/connections?from=8575201&to=8503000
*/
export function TravelsScreen({navigation}) {
const [isLoading, setLoading] = useState(true);
const [travels, setTravels] = useState([]);
useEffect(() => {
fetch('http://transport.opendata.ch/v1/connections?from=8575201&to=8503000')
.then(response => response.json())
.then(json => setTravels(json.connections))
.catch(error => console.error(error))
.finally(() => setLoading(false));
}, []);
return (
<View style={{flex: 1, padding: 24}}>
{isLoading ? (
<ActivityIndicator />
) : (
<FlatList
data={travels}
renderItem={({travel}) => <Text>Travel: {console.log(travel)}</Text>}
keyExtractor={travel => travel.from.departureTimestamp.toString()}
/>
)}
</View>
);
}
Please update your FlatList to :
<FlatList
data={travels}
renderItem={({item}) => {console.log(item)}}
//other properties
/>
From official documentation the renderItem method takes out item from the FlatList array and since you are using the destructuring syntax to extract it, you should explicitly use item. An alternative without the destructuring syntax would look like :
<FlatList
data={travels}
renderItem={(travel) =>{ console.log(travel.item)}}
//other properties
/>

React not being able to acess a query value

Hey i am trying to access whats inside of a fetch trought item.name and so on..
I would like to know why i am not being able to access the item properties
However i am not getting anythign back in the return statement, this is the json i need to access.
{"message":{"_id":"5ea9c860ea9fb600178ae676","name":"frutology","description":"frutas"}}
import React, {useState,useEffect} from 'react';
function StoreDetails ({ match }) {
useEffect(()=>{
fetchItem();
},[]);
const[item,setItem]=useState({name: "", description : ""});
const fetchItem = async() => {
const fetchItem = await fetch(
`/storedisplay/${match.params.id}`
);
const item = await fetchItem.json();
setItem(item);
console.log(item);
}
return (
<div>
<h1>{item.name}</h1>
<h2> {item.description}</h2>
</div>
);
}
export default StoreDetails;
Keep in mind that useState is asynchronous.
Use useEffect.
useEffect(() => {
console.log(item);
}, [item])

JSON data from S3 text file using React

I'm trying to get JSON data from an s3 bucket using React (in a Gatsby project).
This is my code.
import React from 'react';
function getJson() {
return fetch("http://secstat.info/testthechartdata.json")
.then((response) => response.json())
.then((responseJson) => {
return <div>{responseJson[0]}</div>;
})
.catch((error) => {
console.error(error);
});
};
export default getJson;
This is the error I get.
Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
How should I do this? There is probably an easy way to do this in Gatsby but I was going to use React.
Your code has 2 issues:
You can't return a component that waits to Promise.
Fetching a cross domain assets will require CORS headers in your S3
You should refactor it to something like this:
import React, { useState, useEffect } from 'react';
function getJson() {
return fetch('http://secstat.info/testthechartdata.json')
.then(response => response.json())
.catch(error => {
console.error(error);
});
}
const MyComp = () => {
const [list, setList] = useState([]);
useEffect(() => {
getJson().then(list => setList(list));
}, []);
return (
<ul>
{list.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
};
export default MyComp;