I am trying to implement pagination. I am fetching array of 10 items in every fetch request and saving them in state when onEndReached of listview will called I am fetching next items and so on.
My problem is when I am fetching next array of items, the items from previous fetch which are saved in state they are vanishing. and as I updating the state only currently fetched items are displaying.
I want that items from previous fetch should not vanishes on next fetch. Can I append the new items to the existing state? If yes how can I do it?
If I am going wrong then how can I achieve this using any component of react native which is I am unaware of?
Here is my code
constructor(props) {
super(props);
this.state = {
next: "",
qwerty: []
};
this.fetchData = this.fetchData.bind(this);
}
fetchData() {
return fetch('https://shopconapp.herokuapp.com/api/pagination/')
.then((response) => response.json())
.then((responseData) => {
if (!responseData) {
navigate("Login");
} else {
console.log(responseData);
let ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
this.setState({
nexturl: responseData.next,
qwerty: ds.cloneWithRows(responseData.results.post),
});
}
})
}
_onEndReached(){
url = this.state.nexturl;
return fetch(this.state.nexturl)
.then((response) => response.json())
.then((responseData) => {
if (!responseData) {
navigate("Login");
} else {
console.log(responseData);
let ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
this.setState({
nexturl: responseData.next,
qwerty: ds.cloneWithRows(responseData.results.post),
});
}
})
}
<ListView
dataSource={this.state.qwerty}
onEndReachedThreshold={2}
onEndReached={this._onEndReached.bind(this)}
/>
add posts to your state
this.state = {
next: "",
posts : []
qwerty: []
};
for the fetchData method save the state of posts
fetchData() {
return fetch('https://shopconapp.herokuapp.com/api/pagination/')
.then((response) => response.json())
.then((responseData) => {
if (!responseData) {
navigate("Login");
} else {
console.log(responseData);
let ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
this.setState({
nexturl: responseData.next,
posts : responseData.results.post ,
qwerty: ds.cloneWithRows(responseData.results.post),
});
}
})
}
now in onEndReach append the new posts to previous posts and make your data source from the state
_onEndReached(){
url = this.state.nexturl;
return fetch(this.state.nexturl)
.then((response) => response.json())
.then((responseData) => {
if (!responseData) {
navigate("Login");
} else {
console.log(responseData);
let posts = this.state.posts.concat(responseData.results.post);
let ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
this.setState({
nexturl: responseData.next,
posts : posts ,
qwerty: ds.cloneWithRows(posts),
});
}
})
}
You can use ES6 syntax to update the array:
let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.setState({
nexturl: responseData.next,
qwerty: ds.cloneWithRows([...this.state.qwerty, ...responseData.results.post]),
});
Related
#param {authAndGHData} An array with our Auth object and the GitHub data.
module.exports.createSlides = (authAndGHData) => new Promise((resolve, reject) => {
console.log('creating slides...');
const [auth, ghData] = authAndGHData;
// First copy the template slide from drive.
drive.files.copy({
auth: auth,
fileId: '1toV2zL0PrXJOfFJU-NYDKbPx9W0C4I-I8iT85TS0fik',
fields: 'id,name,webViewLink',
resource: {
name: SLIDE_TITLE_TEXT
}
}, (err, presentation) => {
if (err) return reject(err);
const allSlides = ghData.map((data, index) => createSlideJSON(data, index));
slideRequests = [].concat.apply([], allSlides); // flatten the slide requests
slideRequests.push({
replaceAllText: {
replaceText: SLIDE_TITLE_TEXT,
containsText: { text: '{{TITLE}}' }
}
})
I'm need to 'Nodejs' and 'Serveless'. I've created a 'Serverless' API and deployed to AWS. Everything works as expected. The issue i have and i can't seem to find anything about this is, on every second call i get an internal server error. the first call is, returns data as expected.
I've deployed to AWS only in a dev stage. I'm wondering if there is some configuration i'm missing or something?
If you need the 'Serverless' config or code examples i can provide.
Thanks.
ANSWER
I think there was an issue with the DB call not returning data in time for the callback, therefore i was finding inconsistent results.
So basically what i did was create a Database class returning Promises like so...
'use strict';
const mysql = require('mysql');
/**
* Database
*/
class Database {
constructor(config) {
if (!this.dbConnection) {
console.log('connect to DB');
this.dbConnection = mysql.createPool(config);
this.dbConnection.on('connection', (connection) => {
console.info('Connection Made!');
});
}
}
query(sql, args) {
return new Promise((resolve, reject) => {
this.dbConnection.query(sql, args, (err, rows) => {
if (err) {
reject(err);
}
resolve(rows);
})
});
}
close() {
return new Promise((resolve, reject) => {
this.dbConnection.end((error) => {
if (error) {
reject(error);
}
resolve();
});
});
}
}
module.exports = Database;
So when i made my query there was a result ready for the callback.
'use strict';
const Database = require('./lib/Database');
const {successResponse, errorResponse} = require('./lib/response');
const CategoryResource = require('./resource/Category');
module.exports.list = (event, context, callback) => {
let sql = 'SELECT * FROM categories AS c WHERE c.company_id = ? AND c.parent_id IS NULL AND c.status = 1 LIMIT ?, ?;';
const company = parseInt(event.queryStringParameters.company);
let page = 1;
let limit = 20;
if (null != event.queryStringParameters) {
if ('page' in event.queryStringParameters) {
page = parseInt(event.queryStringParameters.page);
}
if ('limit' in event.queryStringParameters) {
limit = parseInt(event.queryStringParameters.limit);
}
}
let start = (page - 1) * limit;
if (isNaN(company)) {
callback(null, errorResponse(400, 'Company ID Required', 'Parameter company_id is required.', []));
return;
}
let Category = new Database();
let categoryResource = [];
Category
.query(sql, [company, start, limit])
.then(response => {
Category.close();
response.forEach((category) => {
categoryResource.push(CategoryResource(category));
});
callback(null, successResponse(200, {
"total": response.length,
"perPage": limit,
"currentPage": page,
"data": categoryResource
}));
})
.catch((error) => {
callback(null, errorResponse(error.code, error.sqlMessage, error.sql, {
code: error.errno,
field: error.sqlMessage,
message: error.sqlMessage
}));
Category.close();
});
};
I hope that helps anyone that may have run into the same issue.
If every other time you get an internal server error, that means your code is syntactically sound but has some sort of logic error. It's impossible to help without example code, but some of the more common errors I've seen that only sometimes occur can be:
race conditions (if you're doing parallel access of the same array, for example)
array access errors (length+1 instead of length-1, less-than-zero, or your iterators are jumping someplace in memory they shouldn't)
simply mentioning the wrong variable (putting an i instead of a j, for example)
Unfortunately, without specific examples, the best we can offer is wild speculation and personal experience. Have you tried looking at AWS's CloudWatch and what it says about your execution? There should be some errors logged in there too.
I think there was an issue with the DB call not returning data in time for the callback, therefore i was finding inconsistent results.
So basically what i did was create a Database class returning Promises like so...
'use strict';
const mysql = require('mysql');
/**
* Database
*/
class Database {
constructor(config) {
if (!this.dbConnection) {
console.log('connect to DB');
this.dbConnection = mysql.createPool(config);
this.dbConnection.on('connection', (connection) => {
console.info('Connection Made!');
});
}
}
query(sql, args) {
return new Promise((resolve, reject) => {
this.dbConnection.query(sql, args, (err, rows) => {
if (err) {
reject(err);
}
resolve(rows);
})
});
}
close() {
return new Promise((resolve, reject) => {
this.dbConnection.end((error) => {
if (error) {
reject(error);
}
resolve();
});
});
}
}
module.exports = Database;
So when i made my query there was a result ready for the callback.
'use strict';
const Database = require('./lib/Database');
const {successResponse, errorResponse} = require('./lib/response');
const CategoryResource = require('./resource/Category');
module.exports.list = (event, context, callback) => {
let sql = 'SELECT * FROM categories AS c WHERE c.company_id = ? AND c.parent_id IS NULL AND c.status = 1 LIMIT ?, ?;';
const company = parseInt(event.queryStringParameters.company);
let page = 1;
let limit = 20;
if (null != event.queryStringParameters) {
if ('page' in event.queryStringParameters) {
page = parseInt(event.queryStringParameters.page);
}
if ('limit' in event.queryStringParameters) {
limit = parseInt(event.queryStringParameters.limit);
}
}
let start = (page - 1) * limit;
if (isNaN(company)) {
callback(null, errorResponse(400, 'Company ID Required', 'Parameter company_id is required.', []));
return;
}
let Category = new Database();
let categoryResource = [];
Category
.query(sql, [company, start, limit])
.then(response => {
Category.close();
response.forEach((category) => {
categoryResource.push(CategoryResource(category));
});
callback(null, successResponse(200, {
"total": response.length,
"perPage": limit,
"currentPage": page,
"data": categoryResource
}));
})
.catch((error) => {
callback(null, errorResponse(error.code, error.sqlMessage, error.sql, {
code: error.errno,
field: error.sqlMessage,
message: error.sqlMessage
}));
Category.close();
});
};
I hope that helps anyone that may have run into the same issue.
I am using jest for unit testing of a react-native app. I have used AsyncStorage in one of my component.
componentWillMount() {
this.setState({ avatarSource: null });
AsyncStorage.getItem('UserDetails', (err, result) => {
var objData = JSON.parse(result);
this.setState({ userdetail: objData });
axios.get(SERVER_URL + '/image/' + objData.userId + '.jpg' + '?$' + Math.random())
.then(response => {
var obj = { uri: response.config.url };
this.setState({ avatarSource: obj });
});
});
}
How do I mock the 'result' from AsyncStorage in my test file?
The best way to test the get method is:
describe('Verifying getData function returns the right value', () => {
it('Function getData must return the correct value given date', async function () {
await getData('SOME_KEY');
expect(AsyncStorage.getItem).toBeCalledWith('SOME_KEY');
});
});
I'm trying to test a component, which uses a service that makes async http calls. The service returns an Observable, which the component subscribes on.
Service code snippet:
getRecentMachineTemperatures(_machine_Id): Observable<IDeviceReadings[]> {
return this.http.get(TemperatureService.URL + _machine_Id)
.map(response => { return response.json(); })
.map((records: Array<any>) => {
let result = new Array<IDeviceReadings>();
if (records) {
records.forEach((record) => {
let device = new IDeviceReadings();
device.device_id = record.device_id;
if (record.d) {
record.d.forEach((t) => {
let temperature = new ITemperature();
temperature.timestamp = t.timestamp;
temperature.value = t.temperature;
device.temperatures.push(temperature);
});
}
result.push(device);
});
}
return result;
});
}
Component code snippet:
ngOnInit() {
this.getRecentTemperatures();
}
getRecentTemperatures() {
this.temperatureService.getRecentMachineTemperatures(this.machine_id)
.subscribe(
res => {
let device1 = res[0];
this.deviceId = device1.device_id;
this.initTemperatures(device1.temperatures);
this.updateChart();
},
error => console.log(error));
}
My Test sets up dependencies, spies on the service 'getRecentMachineTemperatures' and sets i to return some stub data. I've been googling around for ways to test this, thus resulting in 3 different test, trying to test the same thing. Each giving me a different error.
temperature.component.spec.ts:
let machine_id = 1;
let comp: TemperatureComponent;
let fixture: ComponentFixture<TemperatureComponent>;
let de: DebugElement;
let el: HTMLElement;
let temperatureService: TemperatureService;
let stubDevices: IDeviceReadings[];
let stubTemperatures: ITemperature[];
let spyRecentTemps: Function;
describe('Component: Temperature', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [TemperatureComponent],
imports: [ ChartsModule ],
providers: [
MockBackend,
BaseRequestOptions,
{ provide: Http,
useFactory: (backend, defaultOptions) => {
return new Http(backend, defaultOptions);
},
deps: [MockBackend, BaseRequestOptions]},
TemperatureService
]
});
stubDevices = new Array<IDeviceReadings>();
let stubDevice = new IDeviceReadings();
stubDevice.device_id = 'stub device';
stubDevice.temperatures = new Array<ITemperature>();
let stubTemp = new ITemperature();
stubTemp.timestamp = new Date().getTime();
stubTemp.value = 10;
stubDevice.temperatures.push(stubTemp);
stubDevices.push(stubDevice);
stubTemperatures = new Array<ITemperature>();
let stubTemp2 = new ITemperature();
stubTemp.timestamp = new Date().getTime() + 1;
stubTemp.value = 11;
stubTemperatures.push(stubTemp2);
fixture = TestBed.createComponent(TemperatureComponent);
comp = fixture.componentInstance;
temperatureService = fixture.debugElement.injector.get(TemperatureService);
spyRecentTemps = spyOn(temperatureService, 'getRecentMachineTemperatures')
.and.returnValue(Observable.of(stubDevices).delay(1));
// get the "temperature-component" element by CSS selector (e.g., by class name)
de = fixture.debugElement.query(By.css('.temperature-component'));
el = de.nativeElement;
});
it('should show device readings after getRecentTemperatures subscribe (fakeAsync)', fakeAsync(() => {
fixture.detectChanges();
expect(spyRecentTemps.calls.any()).toBe(true, 'getRecentTemperatures called');
tick(1000);
fixture.detectChanges();
expect(el.textContent).toContain(stubDevices[0].temperatures[0].timestamp);
expect(el.textContent).toContain(stubDevices[0].temperatures[0].value);
}));
it('should show device readings after getRecentTemperatures subscribe (async)', async(() => {
fixture.detectChanges();
expect(spyRecentTemps.calls.any()).toBe(true, 'getRecentTemperatures called');
fixture.whenStable().then(() => {
fixture.detectChanges();
expect(el.textContent).toContain(stubDevices[0].temperatures[0].timestamp);
expect(el.textContent).toContain(stubDevices[0].temperatures[0].value);
});
}));
it('should show device readings after getRecentTemperatures subscribe (async) (done)', (done) => {
async(() => {
fixture.detectChanges();
expect(spyRecentTemps.calls.any()).toBe(true, 'getRecentTemperatures called');
fixture.whenStable().then(() => {
fixture.detectChanges();
expect(el.textContent).toContain(stubDevices[0].temperatures[0].timestamp);
expect(el.textContent).toContain(stubDevices[0].temperatures[0].value);
}).then(done);
});
});
});
fakeAsync fails with: 'Error: 1 timer(s) still in the queue.'
async fails with: 'Error: Cannot use setInterval from within an async zone test.'
async (done) fails with: 'Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.'
How would I go about testing components with a async service dependency?
From what I understand it might be something about the AsyncScheduler within the Rx library using Date().now instead of faked time (https://github.com/angular/angular/issues/10127). If so has this been fixed? Or anyone found a workaround?
I'm using angular-cli: 1.0.0-beta.16. node: 4.4.2. npm: 3.10.6. webpack 2.1.0-beta.22.
I had ..
import 'rxjs/add/operator/timeout';
return this.http[method](url, emit, this.options)
.timeout(Config.http.timeout, new Error('timeout'))
Which was causing this error. I believe under the hood RXJS .timeout is calling setInterval.
I fixed this by switching ...
it('blah', async(() => {
to
it('blah', (done) => {
I've went over a lot of examples both here on SO and in some guides/blogs. Nothing seems to work.
I have a customer that hasMany loads
currently the code is:
route
export default Ember.Route.extend({
setupController: function(controller, model) {
controller.setProperties(model);
},
model: function() {
return Ember.RSVP.hash({
content: this.store.createRecord('truck-load'),
customerList: this.store.findAll('customer'),
equipmentList: this.store.findAll('equipment-list')
});
},
resetController(controller, isExisting) {
if (isExisting) {
var model = controller.get('model');
if (model.get('isNew')) {
model.destroyRecord();
}
}
}
});
select box in the template - materialize add on for ember-cli
{{md-select content=customerList
value=model.customer
label="Customer"
prompt="Please Choose a Customer..."
optionLabelPath='content.name'
optionValuePath='content.id'}}
Current controller - I've tried this many ways
export default Ember.Controller.extend({
actions: {
save() {
var truckload = this.get('model');
this.get('model.customer').then((customer) => {
truckload.set('customer', customer);
truckload.save().then((load) => {
this.get('notify').success('Truck Load Created');
this.transitionToRoute('truck-loads.show', load.id);
});
});
JSON for my JSON-API server running Elixir/Phoenix
Parameters: %{"data" => %{"attributes" => %{"pro_number" => "423432", "special" => nil, "status" => nil},
"relationships" => %{"customer" => %{"data" => nil},
"equipment_list" => %{"data" => nil}}} }
customer (and equipment-list) are both coming over nil.
This fixed it.
1) Settings the drop down result as a controller property
2) Accessing this to lookup the model and set it.
selectedCustomer: null,
selectedEquipment: null,
actions: {
save() {
var truckload = this.get('model');
var customer_id = this.get('selectedCustomer');
var equipment_id = this.get('selectedEquipment')
this.store.findRecord('customer', customer_id).then((customer) => {
truckload.set('customer', customer);
this.store.findRecord('equipmentList',equipment_id).then((equipment) => {
truckload.set('equipmentList', equipment);
truckload.save().then((load) => {
this.get('notify').success('Truck Load Created');
this.transitionToRoute('truck-loads.show', load.id);
});
});
});
return false;
},
I doubt this is the best way to do it - but - it DOES work.