Trying to fetch a specific record in JSON file - json

I am trying to fetch just one record from my JSON file, the JSON file is in the public folder
I set up a codesandbox https://codesandbox.io/live/7gu09fv
What is happening now is that it just returns the first record from the JSON and isn't matching the id to pageId
import React, { useState, useEffect } from 'react';
import {
useLocation
} from "react-router-dom";
function FetchContent( { pageId } ) {
const [page, setPage] = useState([]);
useEffect(() => {
fetch("pages.json" ,{
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then(res => res.json())
.then(json =>{
setPage(json)
}
)
}, []);
const found = page.find(id => id = { pageId });
if (!found) return <div />;
return (
<>
<h1 key={found.id}>{found.title.rendered}: {found.id} : {pageId}</h1>
</>
);
}
function Page() {
const { state: { pageId } } = useLocation();
return (
<div className="container-fluid">
<FetchContent pageId={pageId} />
</div>
);
}
export default Page;

import React, { useState, useEffect } from "react";
import { useLocation } from "react-router-dom";
function FetchContent({ pageId }) {
const [foundItem, setFoundItem] = useState();
useEffect(() => {
fetch("pages.json", {
headers: {
"Content-Type": "application/json",
Accept: "application/json"
}
})
.then((res) => res.json())
.then((json) => {
const found = json.find(({id}) => (id === pageId));
setFoundItem(found);
});
}, [pageId]);
if (!foundItem) return <div />;
return (
<>
<h1 key={foundItem.id}>
{foundItem.title && foundItem.title.rendered ? foundItem.title.rendered: ''}: {foundItem.id} : {pageId}
</h1>
</>
);
}
function Page() {
const location = useLocation();
const [pageId, setPageId] = useState(null);
useEffect(()=> {
if(location.state){
setPageId(parseInt(location.state.pageId, 10));
}
}, [location]);
return (
<div className="container-fluid">
<FetchContent pageId={pageId} />
</div>
);
}
export default Page;

Try this:
const found = page.find(obj => obj.id === pageId);

Related

Trying to retrive JSON Array through fetch in react native but JSON parse error:Unreconised token "<"

In the code,i am fetching the token from expo-secure-store,later fetching the API data from fetchdata function.But unfortunately error "unrecognized token" is displayed.
After the error is displayed,the API call returns JSON Array data.Unable to do data map in react native to TradeCard Component.
import { StatusBar } from 'expo-status-bar';
import {React,useState,useEffect} from 'react';
import TradeCard from './TradeCard';
import { StyleSheet, Text, View,TextInput,TouchableOpacity,ScrollView,ActivityIndicator } from 'react-native';
import * as SecureStore from 'expo-secure-store';
export default function Trades()
{
const [ data,setData] = useState([]);
const [ isLoading,setLoading] = useState(true);
const [user,setUser] = useState('');
const [token,setToken] = useState('');
const fetchTokens = async () => {
try {
const user = await SecureStore.getItemAsync('user');
const token = await SecureStore.getItemAsync('token');
setUser(user);
setToken(token);
if (user && token)
{
fetchData();
}
else
{
}
} catch (e) {
alert('Error',e);
}
}
useEffect(()=>{ fetchTokens()},[]);
const fetchData = async () => {
setLoading(true);
fetch('https://tradecoaster.herokuapp.com/api/v1/listTrades/'+user+'/',
{
method:'GET',
headers:{
'Accept':'application/json',
'Content-Type':'application/json',
'Authorization':'token '+token
}
})
.then(res => res.json())
.then((res)=>{
console.log('Data',res);
setData(res);
setLoading(false);
})
.catch((error)=>{
setLoading(false);
alert(error);
console.error("Error",error);
});
}
return(
<ScrollView>
<View>
{isLoading && data.length==0 ? <ActivityIndicator size="large" color="#0000ff" /> :
<Text>No Trades</Text>
}
</View>
</ScrollView>
);
}```

How to fetch data from a specific user

So my question is, how do i link every Item to the right users and how to fetch the data right?
I want ever user in my json db to have a multiple goalItems. As every User has a unique Id, for fetching the data only from the specific user i tried by using "fetch ('http://localhost:5000/goalItems? usersId={usersId}')" but it didn't work.
Down Below you can find the DB.json file, the FULLGOAl Component, thats where the data is fetched and the GoalItem-Component
DB.JSON
{
"users": [
{
"id": "1",
"name": "Jules",
"logindate": ""
}
],
"goalItems": [
{
"id": 1,
"usersId": "",
"text": "XY",
"completed": false,
"completedDate": "18.2.2022, 14:18:24",
"note": "XY"
},
{
"id": 2,
"usersId": "",
"text": "ZY",
"completed": true,
"completedDate": "17.2.2022, 16:40:56",
"note": "ZY"
}
]
}
FullGoal this is where the data is fetched
import React, {useState, useEffect} from 'react'
import GoalItems from './GoalItems'
import DropDownMenu from "./DropDownMenu"
import CompletedLevelPopUp from './CompletedLevelPopUp'
import {useParams} from "react-router-dom";
import levelBatch1 from "./Icons/LevelBatch1.svg"
import levelBatch2 from "./Icons/LevelBatch2.svg"
const levelOption ={
1:
["A",
"B",
"C"
],
2: ["D",
"E",
"F"
}
const FullGoal = ({setNextLevelOpen}) => {
const [editLevel, setEditLevel] = useState(true)
const [goalItems, setGoalItems] = useState ([])
const [completedDate, setCompletedDate] = useState (false)
useEffect (() => {
var completedItems = []
goalItems.forEach(g => g.completed === true | completedItems.push(g.completed))
console.log(completedItems)
if(completedItems.length > 0){
function allCompl(element) {
return element === true
}
completedItems.every(allCompl) ? setOpenPopup (true) : setOpenPopup(false)
}
}, [goalItems])
useEffect (() => {
const getGoalItems = async () => {
const goalItemsFromServer = await fetchGoalItems()
setGoalItems(goalItemsFromServer)
}
getGoalItems()
}, [])
// Fetch Goals
const fetchGoalItems = async () => {
const res = await fetch ('http://localhost:5000/goalItems? usersId={usersId}')
const data = await res.json()
return data
}
//Fetch Goal
const fetchGoal = async (id) => {
const res = await fetch (`http://localhost:5000/goalItems/${id}`)
const data = await res.json()
return data
}
const addGoal = async (goal, id) =>{
const res = await fetch (`http://localhost:5000/goalItems`, {
method:'POST',
headers:{
'Content-type': 'application/json'
},
body: JSON.stringify(goal)
})
const data= await res.json ()
setGoalItems([...goalItems, data])
}
const toggleChecked = async (id) =>{
const goalToToggle = await fetchGoal(id)
const updatedGoal = {...(goalToToggle), completed : !goalToToggle.completed , completedDate : new Date().toLocaleString() + ""}
const res = await fetch (`http://localhost:5000/goalItems/${id}`, {
method: 'PUT',
headers: {
'Content-type': 'application/json',
},
body: JSON.stringify(updatedGoal)
})
const data = await res.json()
setGoalItems(goalItems.map((goal)=> goal.id === id
? {...(goal), completed: data.completed, completedDate:data.completedDate} : goal
))}
const deleteFromJson = async (id) => {
await fetch(`http://localhost:5000/goalItems/${id}`, {
method: 'DELETE'
})
setGoalItems(goalItems.filter((goal) => goal.id !== id))
}
const noteSaveJson = async (id) => {
goalItems.forEach( async e=> {
const res = await fetch (`http://localhost:5000/goalItems/${e.id}`, {
method: 'PUT',
headers: {
'Content-type': 'application/json',
},
body: JSON.stringify(e)
})
})
}
useEffect (noteSaveJson, [goalItems])
return (
<div className="fullGoal">
<div className="dropDownMenuBox">
{editLevel && <DropDownMenu options={levelOption[level] || [] } onAdd={addGoal}/> }
</div>
<div className="goalItemsBox">
<GoalItems id="goalItemBox"
goalItems={goalItems}
completedDate={completedDate}
onChange={v => {
setGoalItems(v)
}}
onToggle={toggleChecked}
editLevel={editLevel}
onDelete={deleteFromJson} />
</div>
</div>
)
}
export default FullGoal
** THIS IS THE GOALITEM COMPONENT **
import React, {useState} from 'react'
import {TiDelete} from 'react-icons/ti'
import {AiFillCheckCircle} from 'react-icons/ai'
import {CgNotes} from 'react-icons/cg'
const GoalItems = ({goalItems, onToggle, editLevel, onChange, onDelete, completedDate}) => {
const [noteOpen, setNoteOpen] = useState (false)
return (
<>
{goalItems.map((goal, index)=>(
<>
<div key={goal.id} className= {`singleGoalItem ${goal.completed ? 'completed' : ''}`} onDoubleClick={()=>onToggle(goal.id)}>
<h3 id="goalTitle">{goal.text}</h3>
<CgNotes id="goalIconNote" onClick={()=> setNoteOpen(!noteOpen)}/>
{editLevel && <TiDelete id="goalIconDelete" onClick={()=> {
onDelete(goal.id)
goalItems.splice(index, 1)
onChange([...goalItems])
}}/>}
{goal.completed ? <AiFillCheckCircle id="goalIconCheck"/> : ''}
</div>
<div>
{noteOpen? <div className="noteBox">
<textarea title="Note"
type ="text"
value= {goal.note}
onChange= {(e)=> {
goalItems[index].note= e.target.value
onChange([...goalItems])}}
placeholder='Füge hier Notizen, Ideen, Pläne ein'
/> </div> : ""}
</div>
</>
))
}
</>
)
}
export default GoalItems

React Native Download JSON but not displaying in Flatlist

I am trying to download the JSON. React Native is downloading the json but I am not sure why Flatlist is not displaying the items. If I change the data={dummyData} in flatlist to data={MyList} then, the flatlist is able to display.
let viewableItemsChanged = null;
const dummyData = GrabData('http://hunterdata.serveblog.net/10record.json');
const MyList = [
{"id":"0","title":"MyBook0","url":"URLBook-0","image":"image-0" },
{"id":"1","title":"MyBook1","url":"URLBook-1","image":"image-1" },
{"id":"2","title":"MyBook2","url":"URLBook-2","image":"image-2" },
{"id":"3","title":"MyBook3","url":"URLBook-3","image":"image-3" },
{"id":"4","title":"MyBook4","url":"URLBook-4","image":"image-4" },
{"id":"5","title":"MyBook5","url":"URLBook-5","image":"image-5" }];
async function GrabData(TheURL) {
let abc = [];
try {
let response = await fetch(TheURL, {headers: {'Cache-Control' : 'no-cache'}});
let responseJson = await response.json();
console.log(responseJson);
return responseJson;
} catch (error) {
console.error(error);
}
}
const renderItem = ({item}) => {
return <View><Text>{item.title}</Text></View>
}
const List = () => {
return (
<FlatList
style={styles.list}
data={dummyData}
renderItem={renderItem}
/>
)
};
there is an issue with your code. you are calling the async function without await keyword. so it returns undefine response like this. {"_U": 0, "_V": 0, "_W": null, "_X": null}
Please Try this solution.
import React, { useEffect , useState } from 'react';
import { SafeAreaView, View, FlatList, StyleSheet, Text, StatusBar } from 'react-native';
const Item = ({ title }) => (
<View style={styles.item}>
<Text style={styles.title}>{title}</Text>
</View>
);
const App = () => {
const [data, setData] = useState([])
useEffect(() => {
apicall();
},[])
const apicall = async () => {
let dd = await GrabData("http://hunterdata.serveblog.net/10record.json");
setData(dd)
}
const GrabData = async (TheURL) => {
try {
let response = await fetch(TheURL, {headers: {'Cache-Control' : 'no-cache'}});
let responseJson = await response.json();
return responseJson;
} catch (error) {
console.error(error);
}
}
const renderItem = ({ item }) => (
<Item title={item?.title} />
);
return (
<SafeAreaView style={styles.container}>
<FlatList
data={data}
renderItem={renderItem}
keyExtractor={item => item?.id}
/>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: StatusBar.currentHeight || 0,
},
item: {
backgroundColor: '#f9c2ff',
padding: 20,
marginVertical: 8,
marginHorizontal: 16,
},
title: {
fontSize: 32,
},
});
export default App;
You should activate the functions in componentDidMount also try states instead of const

How to pass data from a function in react native component

I have created a Banner Component in React Native and now im trying to add data from a function (seperate .js file) in this component. I want to fetch the data on the inital load from my Home Screen but i dont know how to pass the data from my function. I hope you can help me.
This is my code:
home.js
export function HomeScreen() {
{/*This will cause an error*/}
const [item, setItem] = React.useState([]);
React.useEffect(() => {
{/*Function where i fetch my Data from API */}
getbannerdata().then(res => {
setItem(res)
})
console.log(item)
}, [])
return (
<SafeAreaProvider>
<SafeAreaView style={style.container}>
<View>
{/*Banner Component with Data param*/}
<Banner data={item} />
<Text>Home</Text>
</View>
</SafeAreaView>
</SafeAreaProvider>
);
}
My function:
bannerdata.js
export const getbannerdata = () => {
const [data, setData] = React.useState([])
console.log('Test')
fetch('http://192.168.178.46:8000/intranet/messages/', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
})
.then(res => res.json())
.then(res => {
console.log(res)
setData(res)
})
.catch(error => console.log(error));
return data;
};
I hope you can help me.
You should use useState in your component only not in the function where you fetch data.
bannerdata.js
export const getbannerdata = () => {
return fetch('http://192.168.178.46:8000/intranet/messages/', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
});
};
home.js
import { getbannerdata } from './bannerdata'; //import getbannerdata function and you should provide the path of bannerdata.js
export function HomeScreen() {
const [item, setItem] = React.useState([]);
React.useEffect(() => {
{/*Function where i fetch my Data from API */}
getbannerdata()
.then(res => res.json())
.then(res => {
console.log(res)
setItem(res);
});
.catch(error => console.log(error));
}, []);
return (
<SafeAreaProvider>
<SafeAreaView style={style.container}>
<View>
{/*Banner Component with Data param*/}
<Banner data={item} />
<Text>Home</Text>
</View>
</SafeAreaView>
</SafeAreaProvider>
);
}
Thank you for your help.
This is my final solution.
Its a little bit different but now it works as expected
bannerdata.js
import * as React from 'react';
function getbannerdata(){
return fetch ('http://192.168.178.46:8000/intranet/messages/', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
})
.then((res) => res.json())
.then((resData) => {
return resData;
})
.catch(error => console.log(error))
};
export { getbannerdata }
home.js
import {getbannerdata} from './home/bannerdata.js';
export function HomeScreen() {
const [item, setItem] = React.useState([]);
React.useEffect(() => {
getbannerdata()
.then(res => setItem(res))
}, []);
return (
<SafeAreaProvider>
<SafeAreaView style={style.container}>
<View>
{/*Banner Component with Data param*/}
<Banner data={item} />
<Text>Home</Text>
</View>
</SafeAreaView>
</SafeAreaProvider>
);
}

Trouble display name property from axios fetched json object

https://codesandbox.io/s/currying-voice-toq9t - I am trying to save the json object into the component state, then render the name into the browser.
getProfile() {
axios
.get(
"https://cors-anywhere.herokuapp.com/" +
"https://phantombuster.s3.amazonaws.com....."
)
.then(response => {
this.setState({
profile: {
name: response.data.name
}
});
})
.catch(error => this.setState({ error, isLoading: false }));
}
Your Response data is an array form so,You need to give Index.I hope it will helps you.
getProfile() {
axios
.get(
"https://cors-anywhere.herokuapp.com/" +
"https://phantombuster.s3.amazonaws.com/YRrbtT9qhg0/NISgcRm5hpqtvPF8I0tLkQ/result.json"
)
.then(response => {
this.setState({
profile: {
name: response.data[0].name
}
});
})
.catch(error => this.setState({ error, isLoading: false }));
}
The response.data is an array where in first position there is the information that you are looking for, so the setState should be like this:
this.setState({
profile: {
name: response.data[0].name
}
});
or
const [obj] = response.data;
this.setState({
profile: {
name: obj.name
}
});
Your response.data returns an array.so you need to traverse it inside a loop.
import React from "react";
import ReactDOM from "react-dom";
import axios from "axios";
export class Profile extends React.Component {
constructor(props) {
super(props);
this.state = { profile: [] };
}
componentDidMount() {
this.getProfile();
}
getProfile() {
axios
.get(
"https://cors-anywhere.herokuapp.com/" +
"https://phantombuster.s3.amazonaws.com/YRrbtT9qhg0/NISgcRm5hpqtvPF8I0tLkQ/result.json"
)
.then(response => {
console.log("response: ", response)
this.setState({
profile: response.data
});
})
.catch(error => this.setState({ error, isLoading: false }));
}
render() {
let { name } = this.state.profile;
const { error } = this.state;
return (
<div className="App">
<header className="App-header">
<h1 className="App-title">Profile</h1>
{error ? <p>{error.message}</p> : null}
</header>
<div className="App-feeds" />
<div className="panel-list">
{this.state.profile.map((element) => <p>First Name: {element.name}</p>)}
</div>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Profile />, rootElement);