How to do pagination in react native? - json

i am looking for a nice document explaining well about pagination in react native.I can't find a one i'm looking for.I'm fetching the data from server (set of 15 questions and answers).I want to display single question in a page with a next or previous button at the bottom.How to do this?Now i'm displaying all the 15 questions in a single page with ScrollView. But i want pagination.Please help me.

The library react-native-swiper would be the best to use in such a scenario.The example is mentioned in the following link here.
This library uses ScrollView , with a snap animation effect for each item and also contains the customized next and previous button as mentioned here.

var start=0; // above class
var end=100;
fetchData = () => {
var mydata = realm.objects('Product_Info');
this.setState({dbData: mydata})
console.log("fetch---------- paggingData.start--> " + start);
console.log("fetch---------- paggingData.end--> " + end);
var newData = mydata.filtered('prodId > $0 AND prodId <= $1' , start, end); // TODO Logic fetch Data
let paggingData =[];
paggingData = JSON.parse(JSON.stringify(this.state.paggingData));
Object.keys(newData).map(key => {
paggingData.push(newData[key])
})
this.setState({
paggingData
}, () => {
console.log('Search-------------------------------PAGGGING DATA \n', this.state.paggingData)
})
this.setState({dataProvider: dataProvider.cloneWithRows(paggingData)}) //TODO ... working in RecyclerView both
}
onScroll = () => {
console.log("Scrolling");
}
onEndReached = () => {
console.log("\n\n\n\n\--------------------------------------------Reached to End---------------------------------------------");
start = end;
end = end+100;
this.fetchData()
}
<RecyclerListView
layoutProvider={this.layoutProvider}
dataProvider={this.state.dataProvider}
rowRenderer={this.rowRenderer}
onEndReached={this.onEndReached}
onScroll={this.onScroll}
/>

Related

JSON data into variable

EDIT: I solved that error, however, it only seems to print out just one instance. How can I make it put all the entries into that variable?
I'm a little bit too new to this, but I'm trying. Sorry if the question sounds stupid.
I've configured a JSON server and it works just fine. I can pull out the data successfully, however, the data I receive I'd like to go into a variable so that I can use it later on in another function. For this purpose, I created the variable dategraph. However, it doesn't seem to work good. It doesn't seem to read it outside the $each loop. Any ideas what could it be?
I tried using console.log() in the $each loop and it works fine, however, it won't work outside of it.
function solicitare() {
adresa = "http://localhost:4000/listaexamene?callback=?";
$.getJSON(adresa, function (raspuns) {
$.each(raspuns, function (indice, examen) {
continutDeAfisat = "<div><i>Subiect: " + examen.examId + "</i>, Student: " + examen.studentId + "</div>";
$(continutDeAfisat).appendTo("#datenoi");
var dategraph = {};
dategraph.examId = examen.examId;
dategraph.studentId = examen.studentId;
});
console.log(dategraph);
stringNou = JSON.stringify(dategraph);
console.log(stringNou);
});
}
The error I receive is the following:
You're declaring the variable in an inner scope. So the outer scopes don't know what that variable is. Try:
function solicitare() {
const dategraph = {}; // <---
const adresa = "http://localhost:4000/listaexamene?callback=?";
$.getJSON(adresa, function (raspuns) {
$.each(raspuns, function (indice, examen) {
const continutDeAfisat = "<div><i>Subiect: " + examen.examId + "</i>, Student: " + examen.studentId + "</div>";
$(continutDeAfisat).appendTo("#datenoi");
dategraph.examId = examen.examId;
dategraph.studentId = examen.studentId;
});
console.log(dategraph);
const stringNou = JSON.stringify(dategraph);
console.log(stringNou);
});
}
Avoid using var and use let instead.
Simply doing myNewVariable = {}; will work, but javascript will not be very happy with you. When declaring new variables always use let or const.
Use const when you wont re-assign a value to a variable.
Use let when you will re-assign a value to a variable in the future.
Local Arrow Functions. Instead of doing:
$.getJSON(adresa, function (raspuns) {
$.each(raspuns, function (indice, examen) {
You can do:
$.getJSON(adresa, (raspuns) => {
$.each(raspuns, (indice, examen) => {
The only time you generally don't want to do this, is when you are working with the this keyword in javascript.
Unused local variables i.e. indice in your case, since you aren't using it. People usually do _ to indicate that it's an unused variable. So you can use either do _indice or _, or even easier, just do (, examen).
String interpolation. As you can see, its pretty annoying to do "<div><i>Subject:" + examen.examId + "....". Instead of "" make the string with ``. Then you can do string interpolation with variables like this ${examen.examId}.
This is what I'd do.
function solicitare() {
const dategraph = {};
const adresa = "http://localhost:4000/listaexamene?callback=?";
$.getJSON(adresa, (raspuns) => {
$.each(raspuns, (_, examen) => {
const continutDeAfisat = `<div><i>Subiect: ${examen.examId}</i>, Student: ${examen.studentId}</div>`;
$(continutDeAfisat).appendTo("#datenoi");
dategraph.examId = examen.examId;
dategraph.studentId = examen.studentId;
});
console.log(dategraph);
const stringNou = JSON.stringify(dategraph);
console.log(stringNou);
});
}
If you write your javascript in VS code, I can also recommend to install an extension called prettier which will help format your code and make it more readable.
New question: How can I make it that it saves all the answers from the loop and not just one?
Try this:
First, make dategraph an array. Then we push each result object into the array. So something like this:
function solicitare() {
const dategraph = []; // <--- make array
const adresa = "http://localhost:4000/listaexamene?callback=?";
$.getJSON(adresa, (raspuns) => {
$.each(raspuns, (_, examen) => {
const continutDeAfisat = `<div><i>Subiect: ${examen.examId}</i>, Student: ${examen.studentId}</div>`;
$(continutDeAfisat).appendTo("#datenoi");
// push result into array
dategraph.push({
examId: examen.examId,
studentId: examen.studentId,
});
});
console.log(dategraph);
const stringNou = JSON.stringify(dategraph);
console.log(stringNou);
});
console.log("Final dategraph:", JSON.stringify(dategraph, null, 2));
}

How to filter stacked bar chart?

I found following example for a stacked bar chart with dc.js:
https://dc-js.github.io/dc.js/examples/stacked-bar.html
If I click on some (or several) legend item, I would like the chart to
only show the corresponding items (e.g. red and blue) and
adapt the total numbers to only consider the selected items
I already managed to add some click event to the legend entries:
chart.on('pretransition.hideshow', ()=> {
chart.selectAll('.dc-legend-item')
.on('click', function (data, index, nodeList) {
const stackName = data.name;
if(data.hidden){
chart.showStack(stackName);
} else {
chart.hideStack(stackName);
}
dc.redrawAll();
});
});
This hides some stack but the sum is not shown as expected (multiplie, overlapping values are shown).
=>How can I filter the data correctly?
I also tried to use chart.filter() but that only seems to be able filter the x axis and not the stacks.
Currently, if I hover over a legend entry, the chart already adapts but does not show the wanted behavior.
Thanks to Gordon I found following solution:
Step 1: Create an extra dimension for the stack property:
const stackDimension = crossFilter.dimension(d => d.stackProperty);
Step 2: Create an event handler and filter on that dimension:
const selectedStackNames = [];
const legendItemClickHandler = (data, index, nodeList) => {
const stackName = data.name;
if(selectedStackNames.includes(stackName)){
const index = selectedStackNames.indexOf(stackName);
selectedStackNames.splice(index,1);
} else {
selectedStackNames.push(stackName);
}
if(selectedStackNames.length){
stackDimension.filter((name)=>{
return selectedStackNames.includes(name);
});
} else {
stackDimension.filter(null);
}
dc.redrawAll();
};
chart.on('pretransition.hideshow', ()=> {
chart.selectAll('.dc-legend-item')
.on('click', legendItemClickHandler);
});
Step 3: Highlight selected legend items
chart.on('pretransition.show', ()=> {
chart.selectAll('.dc-legend-item')
.on('click', legendItemClickHandler);
const selectedStackNames = new Set(
stackDimension.top(Infinity)
.map(d=>d.stackProperty)
);
chart.selectAll('.dc-legend-item')
.each((data, index, nodeList)=>{
const node = nodeList[index];
const colorRect = node.children[0];
if(selectedStackNames.has(data.name)){
colorRect.style.outline = "1px solid grey";
colorRect.opacity="";
data.hidden=false;
} else {
colorRect.style.outline = "";
data.hidden=true;
colorRect.opacity="0.3";
}
});
});

Function inside a Function not calling in React Native

I am new to react-native and calling a function inside a fucntion.
I have done as below so far :
Step 1 : Created a function _snapshotToArray to convert the firebase snapshot to Arrray.
_snapshotToArray(snapshot) {
var returnArr = [];
snapshot.forEach(function(childSnapshot) {
var item = childSnapshot.val();
item.key = childSnapshot.key;
returnArr.push(item);
});
return returnArr;
}
Step 2 : Created another function as below and calling _snapshotToArray inside it.
_readUserDataFromFirebaseConsole() {//once and on
firebase.database().ref('Users/').on('value', function (snapshot) {
console.log(this._snapshotToArray(snapshot));
Toast.show(this._snapshotToArray(snapshot),Toast.LONG);
});
}
Talking about this call :
console.log(this._snapshotToArray(snapshot));
When I press CTRL+CLick, it not letting me to navigate to body of the fuction _snapshotToArray.
In Device am getting below error :
_snapshotToArray is not defined
What might be the issue ?
I'm not at my PC right now, so I cannot test it, but from looking at your code, you need to use a different function notation to allow the varibale access of/from parent methods and parent class.
_snapshotToArray = snapshot => {
var returnArr = [];
snapshot.forEach(function(childSnapshot) {
var item = childSnapshot.val();
item.key = childSnapshot.key;
returnArr.push(item);
});
return returnArr;
}
and
_readUserDataFromFirebaseConsole = () => {
firebase.database().ref('Users/').on('value', snapshot => {
console.log(this._snapshotToArray(snapshot));
Toast.show(this._snapshotToArray(snapshot),Toast.LONG);
});
}

Pass a random JSON pair into an aframe component

Edit 3: The code is now working across numerous objects (thanks to Noam) and he has also helped in getting the random function working alongside it. I'll update the code in the question once its implemented.
Edit 2: I've taken #Noam Almosnino's answer and am now trying to apply it to an Array with numerous objects (unsuccessfully). Here's the Remix link. Please help!
Edit: I've taken some feedback and found this page which talks about using a JSON.parse function. I've edited the code to reflect the new changes but I still can't figure out exactly whats missing.
Original: I thought this previous answer would help in my attempt to parse a json file and return a random string and its related pair (e.g Title-Platform), but I couldn't get it to work. My goal is to render the output as a text item in my scene. I've really enjoyed working with A-frame but am having a hard time finding documentation that can help me in this regard. I tried using the following modified script to get text from the Json file...
AFRAME.registerComponent('super', { // Not working
schema: {
Games: {type: 'array'},
jsonData: {
parse: JSON.parse,
stringify: JSON.stringify}
},
init: function () {
var el = this.el;
el.setAttribute('super', 'jsonData', {src:"https://cdn.glitch.com/b031cbf1-dd2b-4a85-84d5-09fd0cb747ab%2Ftrivia.json?1514896425219"});
var hugeArray = ["Title", "Platform",...];
const el.setAttribute('super', {Games: hugeArray});
el.setAttribute('position', {x:-2, y:2, z:-3});
}
});
The triggers are also set up in my html to render the text. My code is being worked on through glitch.com, any help will be much appreciated!
To load the json, I think you need to use an XMLHttpRequest (as Diego pointed out in the comments), when that's loaded, you can set the text through setAttribute.
Here's a basic example on glitch:
https://glitch.com/edit/#!/a-frame-json-to-text
On init it does the request, then when done, it set's the loaded json text onto the entity.
AFRAME.registerComponent('json-text-loader', {
schema: {},
init: function () {
var textEntity = document.querySelector('#text');
var url = 'json/text.json';
var request = new XMLHttpRequest();
request.open( 'GET', url, true );
request.addEventListener( 'load', function ( event ) {
var jsonText = JSON.parse( event.target.response )
textEntity.setAttribute("value", jsonText.text)
} );
request.send( null );
}
});
Updated version: https://glitch.com/edit/#!/peppermint-direction
AFRAME.registerComponent('json-text-loader', {
schema: {},
init: function () {
var textEntity = document.querySelector('#text');
var url = 'json/text.json';
var request = new XMLHttpRequest();
request.open( 'GET', url, true );
request.addEventListener( 'load', function ( event ) {
var games = JSON.parse( event.target.response ).games;
// Get a random game from the list
var randomGame = games[Math.floor(Math.random()*games.length)];
// Get the next game if it's available
var nextGame = null
if (games.indexOf(randomGame) < games.length - 1) {
nextGame = games[games.indexOf(randomGame) + 1]
}
// Build the string for the games
var gameInfo = randomGame.Title + '\n' + randomGame.Developer + '\n\n'
if (nextGame != null) {
gameInfo += nextGame.Title + '\n' + nextGame.Developer + '\n'
}
textEntity.setAttribute("value", gameInfo);
var sceneEl = document.querySelector('a-scene');
sceneEl.querySelector('a-box').setAttribute('material', {src:"https://cdn.glitch.com/4e63fbc2-a1b0-4e38-b37a-9870b5594af8%2FResident%20Evil.jpg?1514826910998"});
});
request.send( null );
}
});

generate check-boxes based on drop-down selection?

In my project, I have a one-to-many relation (a Client has many contacts), Now, I am listing the clients in a Drop-down menu, What i want is, To have the Selected Client's Contacts rendered dynamically as check-boxes.
Here is (the part) of my _form.html.haml, and the jQuery part that sends the Ajax request:
%h4 This meeting is made for :
= f.input :client_id, collection:(Client.all)
%br
%hr
%h4 Assign Contacts:
//HERE WHERE I REALLY WANT THE CHECKBOXES TO BE REDNERED DYNAMICALLY.
= check_box_tag "contact_ids[]", c.id, #meeting.contacts.include?(c)
= c.first_name
%br
:javascript
$(document).ready(function (){
$('#meeting_client_id').change(function(){
var state = $('#meeting_client_id :selected').val();
if(state !== "")
{
$.getJSON('/clients/client_contacts/' + state, function(data){
console.log(data);
})
}
return false;
})
});
and here is my Clients_controller action, that handles the request:
def client_contacts
client = (params[:id])
cou = Contact.where(client_id: client)
#msg = { "success" => "true", "message" => "hello", "count" => cou}
respond_to do |format|
format.html
format.json { render json: #msg }
end
end
Now, in the console, I can see that the request is returning the count, and objects.
and hence I am really new to JS/jQuery , and fairly new to Rails, I really don't know how to take it from here.
Any tips/Articles/links/Helps or advice, is really appreciated.
If the only part you're missing is the creation of checkboxes, you can try something like this;
var output = $("some selector for an element containing the checkboxes");
$('#meeting_client_id').change(function(){
var state = this.value;
if(state !== "") {
$.getJSON("/clients/client_contacts/" + state).done(function(data) {
output.empty(); // clear the container
// assuming data is an array of strings, modify as needed
$.each(data, function () {
// for each array item in the result, create a checkbox
$('<input type="checkbox" value="'+this+'">'+this+'</option>')
.appendTo(output); // append it to the container
});
});
}
});
The important parts I used here is:
$.each() for looping through arrays: http://api.jquery.com/jQuery.each/
$("<html>") syntax for creating a new element: http://api.jquery.com/jQuery/#jQuery2
.appendTo() for attaching to the DOM: http://api.jquery.com/appendTo/
Here is a demo where i'm just using a custom function to fake the ajax call.
http://jsfiddle.net/kK622/1/
try this:
$.getJSON('/clients/client_contacts/' + state, function(data){
console.log(data);
data.each(function(){
var id = data.id;
var name = data.firstName;
//add to new div with id myDiv
$('#myDiv').append('<input name='+ id +' type="checkbox" /> ' + name + '<br />');)
});
});