React Native - Using promises when fetching and returning them to components - react-native

i want to display related data on react native, i have 2 response api
response 1
{
"total": 2,
"data" : [
{
"date" : "2020-12-01",
"time" : "08:00:00"
},
{
"date" : "2020-12-02",
"time" : "09:00:00"
}
]
}
response 2, date is parameter
date : 2020-12-01
{
"total": 2,
"data" : [
{
"date" : "2020-12-01",
"description" : "bla bla bla"
},
{
"date" : "2020-12-01",
"description" : "vla vla vla"
}
]
}
date : 2020-12-02
{
"total": 1,
"data" : [
{
"date" : "2020-12-02",
"description" : "cla cla cla"
}
]
}
how to use promises on fetch and how components return them,
so it can display content descriptions like this

Are you asking how to use promises with Fetch? Or how to take the results of those promises and use them to create a visual component?
It doesn't look like you've put any work into asking this question and it's quite wide ranging, from setting up components, creating fetch requests to an API and formatting them into visual components.
I'd consider starting here for your fetch request:
https://reactnative.dev/docs/network#making-requests
Then look at how they take the text and place it on a screen here:
https://reactnative.dev/docs/network#making-requests
EDIT:
Per the comments below.
You would most likely want to store the results of your request in some form of local state, and pass that state to your FlatList or similar, for instance:
const PromiseExample = () => {
const [listItems, setListItems] = useState([])
useEffect(() => {
async function fetchData() {
const data = await fetch('localhost:3000/data').json()
const otherData = await fetch('localhost:3000/otherData').json()
let joinedData = []
// at this point you would join your two data structures in whatever way you need to and push the joined data to the var.
setListItems(joinedData)
}
}, [])
return (
<FlatList data={listItems} />
)
}

Related

what are the assertions that are used for check the order in below body in api tesing using cypress

This is the body for reorder. How can I do assertions to check the order for particular in array[3]
{
"dimName": "Women's Clothing",
"dimOrder": 2,
"dimType": "wa",
"dimId": "category#womens-clothing",
"dimParent": "category"
},
{
"dimName": "Jewelry 1",
"dimOrder": 1,
"dimType": "wa",
"dimId": "category#jewelry",
"dimParent": "category"
},
{
"dimName": "Handbags",
"dimOrder": 3,
"dimType": "wa",
"dimId": "category#handbags",
"dimParent": "category"
}
If you received the above as a json response in an API test, a couple of quick examples:
Check the order of id's like this
cy.request(...)
.then(response => {
expect(response[0].dimId).to.eq('category#womens-clothing')
expect(response[1].dimId).to.eq('category#jewelry')
expect(response[2].dimId).to.eq('category#handbags')
})
Check the dimOrder field is sequential like this
cy.request(...)
.then(response => {
const dimOrder = response.map(item => item.dimOrder)
expect(dimOrder).to.deep.eq([1,2,3]) // deep because is array matching
})
For easier assertions on a response, especially nested properties, you can use cy-spok. It's also quicker to comprehend.
const spok = require('cy-spok')
cy.request(...)
.its('response.body')
.should(spok({
propertieWithArray: [
{
// you can assert the properties equal exact values
dimName: "Women's Clothing",
dimOrder: 2,
dimType: "wa",
dimId: "category#womens-clothing",
dimParent: "category"
},
{
// you can assert properties meet specifications
dimName: spok.string, // Jewelry 1
dimOrder: spok.number, // 1
dimType: spok.type('string'), // wa
dimId: spok.startsWith('category'), // category#jewelry
dimParent: spok.endsWith('category') // category
},
{
// use combination
dimName: spok.string,
dimOrder: spok.gt(0),
dimType: "wa",
dimId: spok.test(/#/),
dimParent: "category"
}

Fetching nearest events with user location using meetup.com GraphQL API

I am trying to find out a way to fetch nearby events using GraphQL meetup.com API. After digging into the documentation for quite some time, I wasn't able to find a query that suits my needs. Furthermore, I wasn't able to find old, REST, documentation, where, the solution for my case might be present.
Thanks in advance !
This is what I could figure out so far, the Documentation for SearchNode is missing, but I could get id's for events:
query($filter: SearchConnectionFilter!) {
keywordSearch(filter: $filter) {
count
edges {
cursor
node {
id
}
}
}
}
Input JSON:
{ "filter" : {
"query" : "party",
"lat" : 43.8,
"lon" : -79.4, "radius" : 100,
"source" : "EVENTS"
}
}
Hope that helps. Trying to figure out this new GraphQL API
You can do something like this (customize it with whatever fields you want from Event):
const axios = require('axios');
const data = {
query: `
query($filter: SearchConnectionFilter!) {
keywordSearch(filter: $filter) {
count
edges {
cursor
node {
id
result {
... on Event {
title
eventUrl
description
dateTime
going
}
}
}
}
}
}`,
variables: {
filter: {
query: "party",
lat: 43.8,
lon: -79.4,
radius: 100,
source: "EVENTS",
},
},
};
axios({
method: "post",
url: `https://api.meetup.com/gql`,
headers: {
Authorization: `Bearer YOUR_OAUTH_ACCESS_TOKEN`,
},
data,
})

How in store object to get access to parent vue page?

In my vue 2.6/cli 4/vuex 3.1 app I update some data in store vuex, like in src/store/index.js :
userPropStore(context, userProp ) {
bus.$emit( 'beforeUserPropStore', userProp );
let apiUrl = process.env.VUE_APP_API_URL
Vue.http.post(apiUrl + '/personal/user-props', userProp).then(({data}) => {
let userProps= this.getters.userProps
userProps.push({
"id": data.user_props.id,
"name": data.user_props.name,
"value": data.user_props.value,
"created_at": data.user_props.created_at,
})
this.commit('refreshUserProps', userProps);
bus.$emit( 'onUserPropStoreSuccess', data );
}, error => {
console.log('context::')
console.log(context)
console.error(error)
self.$refs.userObserverForm.setErrors(error.body.errors)
});
}, // userPropStore(context, userProp ) {
and using ValidationProvider of vee-validate 3.2 I want to catch server errors (like not unique item)
but I got error :
index.js?4360:847 Uncaught (in promise) TypeError: Cannot read property 'userObserverForm' of undefined
on line
self.$refs.userObserverForm.setErrors(error.body.errors)
If there is a way in store object to get access to parent page, maybe with context, which has : https://imgur.com/a/P4St8Ri
?
Thanks!
This is a very strange implementation.
Obviously self.$refs.userObserverForm.setErrors(error.body.errors) fails because you are NOT in a component, which is where $refs is available.
What you have to do in your catch block is setting the errors in Vuex and then make your component read from there.
Pseudocode follows:
I don't understand what your bus is doing... I guess you use it to send data to your component, but why use Vuex then?
userPropStore(context, userProp ) {
bus.$emit( 'beforeUserPropStore', userProp );
let apiUrl = process.env.VUE_APP_API_URL
Vue.http.post(apiUrl + '/personal/user-props', userProp).then(({data}) => {
let userProps= this.getters.userProps
userProps.push({
"id": data.user_props.id,
"name": data.user_props.name,
"value": data.user_props.value,
"created_at": data.user_props.created_at,
})
this.commit('refreshUserProps', userProps);
bus.$emit( 'onUserPropStoreSuccess', data );
commit('SET_USER_PROPS, data)
}, error => {
console.log('context::')
console.log(context)
console.error(error)
commit('SET_USER_PROPS_ERRORS', error.body.errors)
});
}
The way I've done this in the past is to return the promise that Vue.http.post produces and then do what you want in your component with the failure information:
userPropStore(context, userProp ) {
bus.$emit( 'beforeUserPropStore', userProp );
let apiUrl = process.env.VUE_APP_API_URL
//add return to the line below
return Vue.http.post(apiUrl + '/personal/user-props', userProp).then(({data}) => {
Then over in your component:
loadData() {
this.$store.dispatch('userPropStore').catch((error) => {
this.$refs.userObserverForm.setErrors(error.body.errors)
//any other things you want to do "in component" goes here
});
}

Multiple queries on firebase database fields

I'm currently working on react-native todo application, where you can add tasks, I want to only display tasks that has not been completed or archived, I'm having some difficulties on querying both fields at the same time, this is my code for querying the fields.
const { currentUser } = firebase.auth();
// fetch all tasks
firebase
.database()
.ref(`/users/${currentUser.uid}/tasks`)
.ref.orderByChild("completed").equalTo(false)
//.ref.orderByChild("archived").equalTo(false) - This query is not working
.on("value", snapshot =>
this.setState({ tasks: snapshot.val(), loading: false })
);
}
Can I get some assistance on how to check both fields? I'd like to check the fields because I'd like to only display the tasks on default view that has not been completed or archived, as mentioned earlier. I've taken some look at previous related threads, and i'd definitely wouldn't like to change database structure just because of that, I'm rendering the tasks to flatlist, which can be found below:
_FlatListData = data =>
// data recieved from firebase is (collection) an object with individual tasks
// as separate objects with firebase-defined-id as the key and actual task object as value
// Object.entries breaks down the collection into an array of arrays with 2 elements each
// [0] as the key and [1] as value which is then mapped to get an array of objects combining
// the data and the key value into a single object
Object.entries(data)
.map(d => {
return { ...d[1], key: d[0] };
})
.reverse();
{/* render FlatList only if state.tasks is !empty*/}
{!!this.state.tasks && (
<FlatList
/* Since the data fetched from firebase is not an array but an
object it needs to be converted into a workable array first */
data={this._FlatListData(this.state.tasks)}
renderItem={({ item }) => (
<TaskCard
data={item}
DeleteTask={this.DeleteTask}
UpdateTask={this.UpdateTask}
/>
)}
keyExtractor={item => item.key.toString()}
/>
)}
EDIT:
Here's sample json how my structure looks like:
{
"users" : {
"E9JRDTPLZrSAfc0ERvO0yHJw3am1" : {
"tasks" : {
"-LvkpiUO_uxXcf-BYZqk" : {
"archived" : false,
"body" : "Test",
"completed" : true,
"name" : "Test",
"timestamp" : 1575998646319
},
"-Lvl3qzXylp5H2oOLiaE" : {
"archived" : true,
"body" : "Gh",
"completed" : false,
"name" : "Gg",
"timestamp" : 1576002613305
},
"-Lvl4YE2E_omKrsOjkZs" : {
"archived" : false,
"body" : "Hu",
"completed" : true,
"name" : "Bh",
"timestamp" : 1576002794529
},
"-Lvl4woHR5rhtl_JgkBP" : {
"archived" : true,
"body" : "Vc",
"completed" : false,
"name" : "Bbj",
"timestamp" : 1576002899308
}
}
},
"ZqABgFit8YglimXPPZJNoSeea803" : {
"tasks" : {
"-Lvg7rT7PfFLx1nzEzgg" : {
"archived" : false,
"body" : "Test\nS\nS\nS\nS\nDkdndodn\n\n",
"completed" : true,
"name" : "Twdt",
"timestamp" : 1575919777699
}
}
}
}
}

How To Access All Indexes In Nested Array (Vue-chartjs)

so I am trying to display data on my doughnut chart and I am having issues accessing my data from a nested array. When I use the following it just gives me the selected index of the nested array.
So I am wondering is there something else I need to do the computed data or if there is something I am doing wrong.
here is the computed property
countEngagementsByStatus () {
const selectedWorkflow = this.allWorkflows.filter(workflow => workflow.id === this.workflowKey)
const res = selectedWorkflow.map(({statuses, id}) => ({
workflow_id: id,
statuses: statuses.reduce((acc, cur) => {
const count = this.allEngagements.filter(({workflow_id, status}) => workflow_id === id && status === cur.status).length;
acc.push(count);
return acc;
}, [])
}))
return res
},
And on my doughnut chart I am accessing the data. *note removed styling data to clean up the question
datasetsfull() {
return {
labels: this.mapStatuses[0].statuses,
datasets: [
{
label: 'Data One',
data: [
//this is the line I have issues with
this.countEngagementsByStatus[0].statuses[0]
]
}
]
}
},
here is an image of what I am getting
Now If I do this
data: [
this.countEngagementsByStatus[0]
]
I get this as a result however it cannot access the array of numbers shown
So my question is, am I doing something wrong with computed property or am I accessing the data incorrectly or both? Lol
Here is a Js Fiddle To give an idea
So my issue was I was wrapping the data in an array
data: [
this.countEngagementsByStatus[0].statuses
]
I changed it to this
data: this.countEngagementsByStatus[0].statuses