Concatenation two data from two fetch in react native - react-native

I am sorry for distributing you with stupid question,i have to make notification page ,where i know sender and notification's data,
but i cant concatenated sender and notification's data
let responseJson = await response.json();
console.log(responseJson)
if(responseJson.success){
// this.setState(this.state.data.sender=responseJson.data.sender)
responseJson.data.map(notificationInfo=>{
this.getData(notificationInfo.id,notificationInfo.sender)
})
}
else{
console.log("No notification")
}
Method getdata
..FETCH
const responseJson = await response.json();
this.setState({data:responseJson})
// console.log(responseJson.success)
if(typeof responseJson.success != "undefined"){
this.setState({
data=[...this.state.data,sender]
})
the best answer was like below:
Array [
Object {//sender
"name": "Admin Adminovich",
#someother data
},
Object {
"name": "Test Testovich",
#someother data
},
Object {
"name": "just4ina",
#someother data
},
but I need it like
data:[
Object {
"name": "Test Testovich",
"sender": Object {//sender
"name": "Admin Adminovich",
#someother data
},
Object {
"name": "Test",
"sender": Object {//sender
"name": "Admin Adminovich",
#someother data
},
]
ALL concatenation was not what i want

Related

why cant I save data to database?

Trying to insert form data by this function.
Here is my function:
saveTimeline() {
let formData = new FormData();
formData.append("title", this.title);
formData.append("from", this.from);
formData.append("to", this.to);
formData.append("events[0].year", this.year);
formData.append("events[0].image", this.softCopyUpload);
formData.append("events[0].content", this.content);
formData.append("events[0].audio", this.audioFile);
console.log(formData);
this.$axios
.post(this.$API + "api/v1/admin/timelines/", formData, {
headers: {
Authorization: "Bearer " + this.token,
},
})
.then((res) => {
if (res) {
console.log("success");
}
});
},
Error: "Timeline title must not be set to empty"
Always getting this error. Why ?
Why append is not working ?
My JSON
{
"title": "dvdvds",
"from": 1990,
"to": 2010,
"events": [
{
"year": 1990,
"image": "test.jpg",
"content": "test content",
"audio": "test.mp4"
}
]
}
I have no idea what kind of object "this" is, but are you sure that this.title has been set to something, and is not empty?
Seems like you don't set the form data correctly. The docs suggest something like this for the browser:
const params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);

How to convert from blob URL to binary?

I'm using ImageInput component inside an iterator to upload images in my create form and it generates a structure like this:
"data": {
"items": [
{
"id": 1,
"title": "test",
"subTitle": "test",
"additionalAttributes": {
"price": "3452345"
},
"images": [
{
"src": {
"rawFile": {
"path": "test.jpg"
},
"src": "blob:https://localhost:44323/82c04494-244a-49eb-9d0e-6bca5a3469f7",
"title": "test.jpg"
},
"title": "d"
}
]
}
],
"contact": {
"firstName": "test",
"lastName": "test",
"jobTitle": "test",
"emailAddress": "test#test.com",
"phoneNumber": "23234"
},
"theme_id": 1,
"endDate": "2020-06-19T22:27:00.000Z",
"status": "2"
}
}
What I'm trying to do is sending the image to an API for saving in a folder. Blob URL is an internal object in the browser son it can't be used in the API, so I tried to convert the Blob URL into a binary and send to API.
Following the tutorial I can not get the expected result. Here is my code:
I created a new dataProvider like this:
export const PrivateEventProvider = {
create: (resource: string, params: any) => {
convertFileToBase64(params.data.items[0].images[0].src.src).then(
transformedPicture => {
console.log(`transformedPicture: ${transformedPicture}`);
}
);
const convertFileToBase64 = (file: { rawFile: Blob }) =>
new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = reject;
reader.readAsDataURL(file.rawFile);
});
And I have this error
Unhandled Rejection (TypeError): Failed to execute 'readAsDataURL' on
'FileReader': parameter 1 is not of type 'Blob'.
enter image description here
So my question is, which is the correct way of uploading images to a folder using react-admin?

How could I render a ExtWebComponent Area Chart using Alpha Vantage stock data?

I would like to use Alpha Vanatage stock data in my ExtWebComponent chart. How could I fetch the data and render it in a Cartesian Area chart?
If you've generated an ExtWebComponents project, you could add these 2 files and declare the web component html element tag.
Usage
In the html file like index.html declare my-chart-area which is defined in the web component below.
AreaChartComponent.html - HTML Template
<ext-cartesian
width="1000px"
height="600px"
downloadServerUrl="http://svg.sencha.io"
shadow="true"
insetPadding="25 35 0 10"
axes='[{
"type": "numeric" ,
"position": "left" ,
"fields": [ "1. open" ],
"label": { "rotate": { "degrees": "-30" } },
"grid": { "odd": { "fill": "#e8e8e8" } },
"title": { "text": "Alphabet Inc Stock Data" , "fontSize": "20" }
},
{
"type": "category",
"position": "bottom",
"fields": "time",
"grid": "true",
"title": { "text": "Monthly", "fontSize": "20" }
}]'
legend='{
"type": "sprite",
"position": "bottom"
}'
series='[{
"type": "area" ,
"xField": "time",
"yField": [ "1. open", "2. high", "3. low", "4. close" ],
"title": [ "open", "high", "low", "close" ],
"style": { "stroke": "black" , "lineWidth": "2", "fillOpacity": "0.8" },
"colors": ["#003f5c", "#58508d", "#bc5090", "#ff6361", "#ffa600"]
}]'
platformConfig='{
"phone": { "insetPadding": "15 5 0 0" }
}'>
</ext-cartesian>
AreaChartComponent.js - Web Component
import template from './AreaChartComponent.html'
Ext.require([
'Ext.chart.theme.Midnight',
'Ext.chart.theme.Green',
'Ext.chart.theme.Muted',
'Ext.chart.theme.Purple',
'Ext.chart.theme.Sky',
'Ext.chart.series.Area',
'Ext.chart.axis.Numeric',
'Ext.chart.axis.Category'
]);
class AreaChartComponent extends HTMLElement {
constructor() {
super()
}
connectedCallback() {
this.innerHTML = template;
this._fetchChartData();
}
disconnectedCallback() {
}
attributeChangedCallback(attrName, oldVal, newVal) {
}
/**
* Fetch the chart data from https://www.alphavantage.co/ using an API Key.
*
* TODO Fetch your api key here: https://www.alphavantage.co/support/#api-key
*/
_fetchChartData() {
let me = this;
let apiKey = 'demo';
let stockSymbol = 'GOOGL';
let url = `https://www.alphavantage.co/query?function=TIME_SERIES_MONTHLY&symbol=${stockSymbol}&apikey=${apiKey}`;
fetch(url)
.then(response => {
return response.json();
})
.then(json => {
return me._flattenData(json);
})
.then(jsonflatRows => {
me._renderChart(jsonflatRows);
})
.catch(err => {
console.log("error", err);
})
}
/**
* The goal is to flatten the nested json data, so it's easy to consume in the charts.
* #param json data
* #returns {*[]} array of json data
* #private
*/
_flattenData(json) {
console.log("json=", json);
let jsonTimes = json['Monthly Time Series']
let flatRows = [];
for (let jsonTime in jsonTimes) {
let row = {
"time": jsonTime
};
let jsonNestedTime = jsonTimes[jsonTime];
for (let nestedKey in jsonNestedTime) {
row[nestedKey] = jsonNestedTime[nestedKey];
}
flatRows.push(row);
}
return flatRows.reverse();
}
_renderChart(jsonflatRows) {
console.log('_renderChart jsonflatRows=', jsonflatRows);
let store = Ext.create('Ext.data.Store', {
fields: ["time", "1. open", "2. high", "3. low", "4. close", "5. volume"]
});
store.loadData(jsonflatRows);
let areaChartEl = this.querySelector('ext-cartesian');
areaChartEl.ext.bindStore(store);
}
}
window.customElements.define('my-chart-area', AreaChartComponent);
Source
https://gist.github.com/branflake2267/4652a5d7188dfe0b33d3d02a808d8d74

How to update the state of store when we add new data by api

I am new in React-native and Redux, I am trying to do CRUD operation. How to update the state of store when we add data by api. I am calling Get Business Api in may action. and I store it into Store.
business action:
export const getBusinessByAliases = (aliases) => {
return (dispatch) => {
dispatch(getBusinessByAliasesData(aliases))
//API CALL
getBusiness(aliases)
.then(response=>{
//HERE I GET WHOLE BUSINESS DATA
dispatch(getBusinessByAliasesSuccess(response.data.business))
})
.catch(err => {
console.log("err",err)
dispatch(getBusinessByAliasesFailure(err))
})
}
}
business data is:
business:[
"id": "17bfdde3-bc04-4a9c-87e7-7530ded1b929",
"inserted_at": "2019-07-10T09:47:41",
"name": "Business2",
"employees": [
{
"nickname": "xyz",
"settings": null,
"user": {
"email": null,
"first_name": null,
"id": "582f5d07-146e-4a81-a6c0-7dd5208b43b2",
"image_id": null,
"inserted_at": "2019-07-02T13:41:06",
"last_name": null,
"phone": "+911234567890"
}
}
],
"services": [
{
"id": "34bd8c80-41e1-459a-bc09-d88a6894bd42",
"name": "Gsgsha",
"settings": {
"color": "#039BE5",
"duration": 4,
"price": 6
}
}
],
]
Now i am adding customer by calling create employee api in another action
employee action :
export const createNewEmployee = (businessName,data) => {
//console.log("whole data", data)
return (dispatch) => {
dispatch(createEmployee(businessName,data))
// API CALL
createEmployees(businessName,data)
.then(response=>{
//IN RESPONSE I GET SUCCESS MESSAGE WITH TRANSACTION ID
dispatch(createEmployeeSuccess(response.data.transaction_id))
})
.catch(err => {
console.log("errEmp",err)
dispatch(createEmployeeFailure(err))
})
}
}
Now, How do I update by the business state which contains all data with my new added employee entry?
I think the best solution is that your endpoint should response the new business object with all employes or only the new list of employes.
Keep in mind that your server can be modified by a lot of app clients, if you need to keep the information updated, you need to implement a Firebase protocol to update your store every time.

Unable to loop through data from SQLite call in React Native, Expo

I'm currently making a call to an SQLite local database in my react native
Expo app like so:
db.transaction(tx => {
tx.executeSql('select * from dr_report_templates', [], (_, { rows }) => {
const templateData = JSON.stringify(rows);
this.setState({ options: templateData, isLoading: false }, () => console.log(this.state))
});
},
error => {
alert(error);
},
() => console.log('Loaded template settings')
);
I'm returning the data and making it a JSON string with: JSON.stringify
Data appears like so:
Object {
"isLoading": false,
"options": "{\"_array\":[{\"id\":30,\"name\":\"SFR General\",\"description\":\"SFR1\"},{\"id\":31,\"name\":\"SFR Extended\",\"description\":\"SFR2\"},{\"id\":7790,\"name\":\"test_new_template\",\"description\":\"test_new_template\"},{\"id\":7792,\"name\":\"apart_1\",\"description\":\"apart_1\"},{\"id\":7793,\"name\":\"SFR\",\"description\":\"Single Family\"},{\"id\":7798,\"name\":\"Condo\",\"description\":\"Condo \"},{\"id\":7799,\"name\":\"Duplex\",\"description\":\"Duplex\"},{\"id\":7800,\"name\":\"Triplex \",\"description\":\"3\"},{\"id\":7801,\"name\":\"Apartments\",\"description\":\"Apartment complex\"},{\"id\":7802,\"name\":\"Commercial retail store \",\"description\":\"Storefront \"},{\"id\":7803,\"name\":\"5-10 unit\",\"description\":\"5\"},{\"id\":7804,\"name\":\"Commercial Industrial \",\"description\":\"Industrial \"},{\"id\":7805,\"name\":\"Industrial Property\",\"description\":\"RE\"}],\"length\":13}",
"selected": "",
}
Attempting to get values for just the first array element like so:
this.state.options[0]
does not work. I'm obviously doing something wrong in the way that I'm doing this but can't figure out what. Any ideas?
EDIT: I had also ran the query with out JSON.Stringify. The data returned like so with this "t" in front of it. I've never hard this before and I couldn't loop through it so that's why I did a JSON.stringify.
t {
"_array": Array [
Object {
"description": "SFR1",
"id": 30,
"name": "SFR General",
},
Object {
"description": "SFR2",
"id": 31,
"name": "SFR Extended",
},
Object {
"description": "test_new_template",
"id": 7790,
"name": "test_new_template",
},
Object {
"description": "apart_1",
"id": 7792,
"name": "apart_1",
},
Object {
"description": "Single Family",
"id": 7793,
"name": "SFR",
},
Object {
"description": "Condo ",
"id": 7798,
"name": "Condo",
},
Object {
"description": "Duplex",
"id": 7799,
"name": "Duplex",
},
Object {
"description": "3",
"id": 7800,
"name": "Triplex ",
},
Object {
"description": "Apartment complex",
"id": 7801,
"name": "Apartments",
},
Object {
"description": "Storefront ",
"id": 7802,
"name": "Commercial retail store ",
},
Object {
"description": "5",
"id": 7803,
"name": "5-10 unit",
},
Object {
"description": "Industrial ",
"id": 7804,
"name": "Commercial Industrial ",
},
Object {
"description": "RE",
"id": 7805,
"name": "Industrial Property",
},
],
"length": 13,
}
this.setState({ options: templateData._array, isLoading: false });
or change how you destructure in 3rd parameter of executeSql to:
(_, { rows: { _array } }) => {
const templateData = JSON.stringify(_array);
}
Why you're conveting it with JSON.stringify()? You can iterate over array or access it with array's key name.
NOTE: JSON.stringify() does not convert it to JSON. It converts to JSON string
The JSON.stringify() method converts a JavaScript object or value to a
JSON string, optionally replacing values if a replacer function is
specified or optionally including only the specified properties if a
replacer array is specified.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
You're actually converting your database response to string.
So Change
const templateData = JSON.stringify(rows);
to
const templateData = rows;
and use this array where you want.