I used a fetch API to get data from backend server. I returned JSON object data from fetch function and I want to pass every single value in the object to another object.
function getvals() {
return fetch('http://*********/users/timetable')
.then(response => response.json())
.then((responseData) => {
console.log(responseData);
return responseData;
})
.catch(error => console.log(error))
}
the function getvals() is returning the object data, these data looks like this:
[{"title": "Math","day": "FRI", "end_time": 11, "start_time": 9,location: "Classroom 403",extra_descriptions: "Chen"}]
now I want every single value of the object data to be passed to this object:
const events_data = [
{
title: "Math",
startTime: genTimeBlock("WED", 9),
endTime: genTimeBlock("WED", 10),
location: "Classroom 403",
extra_descriptions: ["Kim", "Lee"],
},
{
title: "Mandarin",
startTime: genTimeBlock("TUE", 9),
endTime: genTimeBlock("TUE", 10),
location: "Language Center",
extra_descriptions: ["Chen"],
},
{
title: "Japanese",
startTime: genTimeBlock("FRI", 9),
endTime: genTimeBlock("FRI", 10),
location: "Language Center",
extra_descriptions: ["Nakamura"],
},
];
for example the value of day from getvals() function i want to pass it to be set in in startTime in events_data object
then within the the view the events_data will be passed to events props:
<SafeAreaView style={{ flex: 1, padding: 30 }}>
<View style={styles.container}>
<TimeTableView
scrollViewRef={this.scrollViewRef}
**events={// events.data will be passed here as object format //}**
pivotTime={8}
pivotDate={this.pivotDate}
numberOfDays={this.numOfDays}
onEventPress={getvals}
headerStyle={styles.headerStyle}
formatDateHeader="dddd"
locale="en"
/>
</View>
</SafeAreaView>
it may the way to do this is easy but im new with this approche and i couldn't find an easy way to do it.
You can map over the data and then add them to the array events_data.
The function addData pushes the data received from the fetch request in the desired format to the events_data.
function getvals() {
fetch("http://*********/users/timetable")
.then((response) => response.json())
.then((output) => {
addData(output, events_data);
})
.catch((error) => console.log(error));
}
function addData(data, data2) {
data.forEach(d) => {
data2.push({
title: d.title,
startTime: genTimeBlock(d.day, d.startTime),
endTime: genTimeBlock(d.day, d.endTime),
location: d.location,
extra_description: [d.extra_description],
});
});
}
Edit:
If you wanted to render the data then you can do it like this:
const RenderData = () => {
return (
<View>
{events_data &&
events_data.result.map((data) => {
return <Text>{data.title}</Text>;
})}
</View>
);
};
Related
Just a simple React Native fetch request to MongoDB database. I'm trying to display dynamic JSON properties for a user's post, for example postedBy, title, etc. But when I set something like title or description I get nothing at all, just blankness.
Post.js
const mongoose = require('mongoose')
const bcrypt = require('bcrypt')
const { ObjectId } = mongoose.Schema.Types
const postSchema = new mongoose.Schema({
title: {
type: String,
required: true
},
postdesc: {
type: String,
required: true
},
img: {
type: String,
required: true
},
postedBy: {
type: ObjectId,
ref: "User"
}
})
mongoose.model("Post", postSchema)
fetch api code
router.get('/allposts', requireLogin, (req, res)=>{
Post.find()
.populate('postedBy', '_id username')
.then( posts =>{
res.json({ posts })
})
.catch( err=>{
console.log(err)
})
})
fetch code
const [ data, setData ] = useState([])
useEffect(()=>{
AsyncStorage.getItem('user')
.then(async (data) => {
fetch('http://10.0.2.2:3000/allposts', {
headers: {
'Authorization': 'Bearer ' + JSON.parse(data).token
}
}).then(res=>res.json())
.then( result=>{
console.log(result)
setData(result.posts)
})
})
}, [])
return code
return(
<View style={styles.container}>
<View style={styles.c1}>
{
data.map(( item )=>{
return(
<View key={item}>
<Text style={styles.postedBy} >{ data.postedBy }</Text>
<Text style={styles.title} >{ data.title }</Text>
</View>
)
})
}
</View>
</View>
)
}
What I want is: The title of my post is "Here is a title from db".
What I'm getting is: The title of my post is [Blank space] .
Note: the console.log(result) is showing the post's json in console just fine.
LOG {"posts": [{"__v": 0, "title": "Here is a title"`...etc, etc }]}
hello I have a nodejs project, I am using sequelize and mysql2 to access the database, in one of its routes I show an ejs view and I want to send a variable to it so that different products/cards are dynamically loaded from a form.
now when I use the findAll() method to call the different mysql records I try to bring an array of objects but it returns the loose objects so in the ejs view I cannot iterate with a foreach() for example
I execute this from a home route
i try this
products_dataBase.findAll()
.then(products => {
products.forEach(element => {
let result = []
result.push( element.dataValues)
res.render('home.ejs', { result });
console.log(result)
});
})
.catch(err => {
console.log(err)
})
[
{
id: 14,
title: 'asdasd',
price: 33434,
description: 'sdasd',
createdAt: 2022-11-08T02:06:12.000Z,
updatedAt: 2022-11-08T02:06:12.000Z
}
]
[
{
id: 15,
title: 'asodfsd',
price: 232,
description: 'asdasd',
createdAt: 2022-11-08T03:17:20.000Z,
updatedAt: 2022-11-08T03:17:20.000Z
}
]
[
{
id: 16,
title: 'ldfsksdf',
price: 343434,
description: 'efsddsff',
createdAt: 2022-11-08T03:17:44.000Z,
updatedAt: 2022-11-08T03:17:44.000Z
}
]
res.render must be executed only once per request, but you invoke it repeatedly, in a forEach loop. Try this:
products_dataBase.findAll()
.then(products => {
let result = [];
products.forEach(element => {
result.push(element.dataValues);
});
res.render('home.ejs', { result });
console.log(result);
})
.catch(err => {
console.log(err);
});
I am getting this error when I console data returned from function that fetch data from back end
{"_U": 0, "_V": 0, "_W": null, "_X": null}
here is below the code:
const events_data = [];
function getvals() {
return fetch('http://PCIP:3000/users/timetable')
.then((response) => response.json())
.then((output) => {
return addData(output, events_data);
})
.catch(error => console.log(error))
}
function addData(data, data2) {
data.map((d) => {
data2.push({
title: d.name,
startTime: genTimeBlock(d.day, d.start_time),
endTime: genTimeBlock(d.day, d.end_time),
location: d.location,
extra_descriptions: [d.extra_descriptions],
});
});
}
const data = getvals();
console.log(data); // the error come from here
I have checked answers here but nothing worked for me
fetch API always returns {“_U”: 0, “_V”: 0, “_W”: null, “_X”: null}
How do I access promise callback value outside of the function?
This is because the fetch promise has not return a response yet,
There two way to solve the issue , first you create another async funciton and use it to await for the response
const events_data = [];
async function getvals() {
return fetch('http://PCIP:3000/users/timetable')
.then((response) => response.json())
.then((output) => {
return addData(output, events_data);
})
.catch(error => console.log(error))
}
function addData(data, data2) {
data.map((d) => {
data2.push({
title: d.name,
startTime: genTimeBlock(d.day, d.start_time),
endTime: genTimeBlock(d.day, d.end_time),
location: d.location,
extra_descriptions: [d.extra_descriptions],
});
});
}
async function waitForResponse() {
let resp = await getvals();
return resp;
}
const data = waitForResponse();
console.log(data); // the error come from here
The other way would be using state hooks, passing the return obj to state hook on response.
Function for API call:
export const getApplication = async (URL, headers) => {
let data;
await fetch.get(URL, headers).then(res => data = res.data).catch(err => err);
return data;
}
You can call the API from anywhere after importing it:
getApplication(`your url`, {
headers: {
Authorization: AUTH_TOKEN,
},
}).then(res => console.log(res)).catch(err => console.log(err));
json file img
Note: I wanna insert data without write that into .json file. such as Angularfire2 database.
user = {
name: 'Arthur',
age: 21
};
const options = {Headers, responseType: 'json' as 'blob'};
this.httpService.put('assets/data/ex.json', this.user, options).subscribe(
data => {
console.log(data);
},
(err: HttpErrorResponse) => {
console.log (err.message);
}
);
You can directly access the object using dot operator
user = {
name: 'Arthur',
age: 21
};
const options = {Headers, responseType: 'json' as 'blob'};
this.httpService.put('assets/data/ex.json', this.user, options).subscribe(
data => {
console.log(data);
data.user.lastName = 'stackoverflow';
},
(err: HttpErrorResponse) => {
console.log (err.message);
}
);
I have a fetch returning on ComponentDidMount(). Trying to get the response to render on the page.
I have set the state as follows:
this.state = {
loading: true,
file: null,
video: null,
marks: []
};
and my fetch:
componentDidMount() {
return fetch('http://10.0.2.2:8080/marks/createMark')
.then(response => response.json())
.then((data) => {
this.setState({
loading: false,
marks: data.mark
}, () => {
console.log(data.mark);
console.log(this.state.marks);
// const dataMap = data.mark.map((item) => {
// return {
// key: item.id,
// label: item.mark
// };
// });
});
})
.catch(err => console.log(err));
}
Now my render inside of the return:
const { marks } = this.state;
<FlatList
data={marks}
renderItem={({ item }) => <Text>{item.mark}</Text>}
keyExtractor={(item, index) => index}
/>
Do I have to map the data then try to render it??
OUTPUT OF console.log(this.state.marks):
{ _id: '5b61e47a55a0000aa980fab1', mark: 'ItHe', __v: 0 }
The mark is a pseudorandom string that can contain letters and numbers created on the backend
As this.state.marks is an object. First, you need to convert it to this form [{}]. You can do the following changes to make it work.
fetch('http://10.0.2.2:8080/marks/createMark')
.then(response => response.json())
.then((data) => {
let marks = [data.mark]; //Add this line
this.setState({
loading: false,
marks: marks // Change this line
}, () => {
....
Rest of your code
marks is an array but you're not sharing what each object in the array looks like. If it's an array of strings, you're good but if it's an object, you'll need to destructure it and pull out the string you're looking to render.
<Text>{item.mark.someKeyWhoseValueIsAString}</Text