how to create a seating layout for bus react native - api

I was wondering to create seat layout for the bus. So, I found this link which show how to create the map of seats.
So following is the response I get from API
{"seats":[{"width":1,"fare":"","zIndex":0,"number":"A1","type":"A1","serviceTaxAmount":"0","convenience_charge":"0","commission":"","operatorServiceChargeAbsolute":"","operatorServiceChargePercent":"0","totalFareWithTaxes":"","ladiesSeat":"","bookedBy":"","ac":"true","sleeper":"","serviceTaxPer":"0","available":"","length":1,"id":"A1","seatid":"A1","row":0,"column":1},{"width":1,"fare":"1000","zIndex":0,"number":"A3","type":"A3","serviceTaxAmount":"0","convenience_charge":"0","commission":"","operatorServiceChargeAbsolute":"","operatorServiceChargePercent":"0","totalFareWithTaxes":"1000","ladiesSeat":"","bookedBy":"","ac":"true","sleeper":"","serviceTaxPer":"0","available":"1","length":1,"id":"A3","seatid":"A3","row":2,"column":1}]}
this is what I did so far
componentDidMount() {
return fetch(seat_url)
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
row: responseJson.seats.row,
column: responseJson.seats.column,
}, function() {
});
})
.catch((error) => {
console.error(error);
});
}
So how to use the above response in adjacent with ROWS and COLS because rows and cols will not be constant it will be dynamic on each row and column. In Example provided from above link cols and rows are fixed. I want to access them dynamically.

Use table component & create Rows, Columns. Install below package
npm install react-native-table-component
import { Table, TableWrapper, Row, Rows, Col, Cols, Cell } from 'react-native-table-component';
let myData1= [];
const rowData1= [];
const type_data= [];
let row_length=[];
let col_length=[];
let type_length=[];
let row_count,col_count,a,b,c,d;
componentDidMount() {
return fetch(seat_url)
.then((response) => response.json())
.then((responseJson) => {
let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
var resultresponse = responseJson.result;
for (var i in resultresponse) {
var seatresponse = resultresponse[i].seats;
for(var j in seatresponse)
{
myData1.push(seatresponse[j]);
row_length.push(seatresponse[j].row);
col_length.push(seatresponse[j].column);
type_length.push(seatresponse[j].type);
rowData1.push(`${seatresponse[j].row},${seatresponse[j].column}`);
}
}
row_count = Array.from(new Set(row_length));
col_count = Array.from(new Set(col_length));
a = row_count.length.toString();
b = col_count.length.toString();
c = row_length.length.toString();
d = col_length.length.toString();
})
}
render() {
const state = this.state;
const tableData1 = [];
const tableData = [];
for (let i = 1; i <= b; i ++) {
rowData = [];
rowData2 = [];
// If table row & col matches with your response row & col then, push the data else assign as NULL.
for (let j = 0; j < a; j ++) {
rowData.push(${j},${i});
for (let k = 0; k <= rowData1.length && k<=type_length.length; k ++) {
if(${j},${i} === rowData1[k])
{
rowData[rowData.indexOf(${j},${i})] = myData1[k];
}
}
for (let l = 0; l <= rowData1.length; l ++) {
if(`${j},${i}` != rowData1[l])
{
rowData[rowData.indexOf(`${j},${i}`)] = 'NULL';
}
}
}
tableData.push(rowData);
}
return (
<View style={styles.MainContainer}>
<Table borderStyle={{borderColor: 'transparent'}} >
<Row style={styles.head} textStyle={styles.text}/>
{
tableData.map((rowData, index) => (
<TableWrapper key={index} style={styles.row}>
{
rowData.map((cellData, cellIndex) => (
<Cell style={{backgroundColor: 'orange', margin:5, height:40, width:40}} key={cellIndex} data={cellData.type} />
))
}
</TableWrapper>
))
}
</Table>
</View>
);
}

Related

React Native updating only after I save file

I have an application that queries the stock exchange in real time, but when I open the application the first time it does not update any displayed value, as if it were hardcoded, but when I save the file (ctrl + S) it starts to update normally , Can anyone help me with this?
description code below:
this function is listening the data on firebase;
ticketRT is my state that is not updating at first time
Object.keys(subscriptionStocks).forEach((stock) => {
if(!subscriptionStocks[stock].listener) {
firebase.database().ref(`${endPointStocks}/${stock}`).on('value', async data => {
let stock = data.val();
if (stock) {
stockArray[stock.ticket] = stock;
setTicketRT(stockArray);
await updateListStocks(stock);
} else {
console.log(`[listenerStock]: Não foi possível cadastrar o ativo "${stock}"`);
}
});
subscriptionStocks[stock].listener = true;
this function updates the stock list
let tmpStock = {};
console.log('LENGTH 11111', stockArray.length);
if (stockArray.length === 0) {
console.log('LENGTH 22222 ≥≥≥ 2', stockArray.length);
tmpStock[stock.ticket] = stock;
stockArray.push(tmpStock);
setTicketRT(stockArray);
updateWalletBalance();
} else {
const foundStockInArray = stockArray.some(
el => {
let inStock = el[Object.keys(el)[0]];
return inStock.ticket == stock.ticket;
}
);
if (foundStockInArray) {
updateStock(stock);
} else {
tmpStock[stock.ticket] = stock;
stockArray.push(tmpStock);
setTicketRT(stockArray);
updateWalletBalance();
}
}
this is my FlatList that is not updating
<FlatList
style={styles.actionList}
showsVerticalScrollIndicator={false}
showsHorizontalScrollIndicator={false}
data={ticketRT}
extraData={(item, index) => {
if(ticketRT !== undefined) {
let stocks = ticketRT[index];
let stock = stocks[Object.keys(stocks)[0]];
return stock.ticket;
}
}}
keyExtractor={(item, index ) => {
if(ticketRT !== undefined) {
let stocks = ticketRT[index];
let stock = stocks[Object.keys(stocks)[0]];
return stock.ticket;
}
}}
renderItem={({ index }) => {
let stocks = ticketRT[index];
let stock = stocks[Object.keys(stocks)[0]];
return <Ativos data={stock} />
}}
contentInset={{ bottom: 10, top: -5 }}
/>
ALL CODE IS FOUNDED HERE: https://gist.github.com/paulorod07/4e74976345a6a68b0e32755cf5ae1c46

How to change the width of NormalPeoplePicker dropdown

I'm using default example of NormalPeoplePicker from https://developer.microsoft.com/en-us/fluentui#/controls/web/peoplepicker#IPeoplePickerProps.
When the dropdown displays it cuts off longer items (example: 'Anny Lundqvist, Junior Manager of Soft..'). How do I make it wider, so that the full item's text displays?
import * as React from 'react';
import { Checkbox } from 'office-ui-fabric-react/lib/Checkbox';
import { IPersonaProps } from 'office-ui-fabric-react/lib/Persona';
import { IBasePickerSuggestionsProps, NormalPeoplePicker, ValidationState } from 'office-ui-fabric-react/lib/Pickers';
import { people, mru } from '#uifabric/example-data';
const suggestionProps: IBasePickerSuggestionsProps = {
suggestionsHeaderText: 'Suggested People',
mostRecentlyUsedHeaderText: 'Suggested Contacts',
noResultsFoundText: 'No results found',
loadingText: 'Loading',
showRemoveButtons: true,
suggestionsAvailableAlertText: 'People Picker Suggestions available',
suggestionsContainerAriaLabel: 'Suggested contacts',
};
const checkboxStyles = {
root: {
marginTop: 10,
},
};
export const PeoplePickerNormalExample: React.FunctionComponent = () => {
const [delayResults, setDelayResults] = React.useState(false);
const [isPickerDisabled, setIsPickerDisabled] = React.useState(false);
const [mostRecentlyUsed, setMostRecentlyUsed] = React.useState<IPersonaProps[]>(mru);
const [peopleList, setPeopleList] = React.useState<IPersonaProps[]>(people);
const picker = React.useRef(null);
const onFilterChanged = (
filterText: string,
currentPersonas: IPersonaProps[],
limitResults?: number,
): IPersonaProps[] | Promise<IPersonaProps[]> => {
if (filterText) {
let filteredPersonas: IPersonaProps[] = filterPersonasByText(filterText);
filteredPersonas = removeDuplicates(filteredPersonas, currentPersonas);
filteredPersonas = limitResults ? filteredPersonas.slice(0, limitResults) : filteredPersonas;
return filterPromise(filteredPersonas);
} else {
return [];
}
};
const filterPersonasByText = (filterText: string): IPersonaProps[] => {
return peopleList.filter(item => doesTextStartWith(item.text as string, filterText));
};
const filterPromise = (personasToReturn: IPersonaProps[]): IPersonaProps[] | Promise<IPersonaProps[]> => {
if (delayResults) {
return convertResultsToPromise(personasToReturn);
} else {
return personasToReturn;
}
};
const returnMostRecentlyUsed = (currentPersonas: IPersonaProps[]): IPersonaProps[] | Promise<IPersonaProps[]> => {
return filterPromise(removeDuplicates(mostRecentlyUsed, currentPersonas));
};
const onRemoveSuggestion = (item: IPersonaProps): void => {
const indexPeopleList: number = peopleList.indexOf(item);
const indexMostRecentlyUsed: number = mostRecentlyUsed.indexOf(item);
if (indexPeopleList >= 0) {
const newPeople: IPersonaProps[] = peopleList
.slice(0, indexPeopleList)
.concat(peopleList.slice(indexPeopleList + 1));
setPeopleList(newPeople);
}
if (indexMostRecentlyUsed >= 0) {
const newSuggestedPeople: IPersonaProps[] = mostRecentlyUsed
.slice(0, indexMostRecentlyUsed)
.concat(mostRecentlyUsed.slice(indexMostRecentlyUsed + 1));
setMostRecentlyUsed(newSuggestedPeople);
}
};
const onDisabledButtonClick = (): void => {
setIsPickerDisabled(!isPickerDisabled);
};
const onToggleDelayResultsChange = (): void => {
setDelayResults(!delayResults);
};
return (
<div>
<NormalPeoplePicker
// eslint-disable-next-line react/jsx-no-bind
onResolveSuggestions={onFilterChanged}
// eslint-disable-next-line react/jsx-no-bind
onEmptyInputFocus={returnMostRecentlyUsed}
getTextFromItem={getTextFromItem}
pickerSuggestionsProps={suggestionProps}
className={'ms-PeoplePicker'}
key={'normal'}
// eslint-disable-next-line react/jsx-no-bind
onRemoveSuggestion={onRemoveSuggestion}
onValidateInput={validateInput}
removeButtonAriaLabel={'Remove'}
inputProps={{
onBlur: (ev: React.FocusEvent<HTMLInputElement>) => console.log('onBlur called'),
onFocus: (ev: React.FocusEvent<HTMLInputElement>) => console.log('onFocus called'),
'aria-label': 'People Picker',
}}
componentRef={picker}
onInputChange={onInputChange}
resolveDelay={300}
disabled={isPickerDisabled}
/>
<Checkbox
label="Disable People Picker"
checked={isPickerDisabled}
// eslint-disable-next-line react/jsx-no-bind
onChange={onDisabledButtonClick}
styles={checkboxStyles}
/>
<Checkbox
label="Delay Suggestion Results"
defaultChecked={delayResults}
// eslint-disable-next-line react/jsx-no-bind
onChange={onToggleDelayResultsChange}
styles={checkboxStyles}
/>
</div>
);
};
function doesTextStartWith(text: string, filterText: string): boolean {
return text.toLowerCase().indexOf(filterText.toLowerCase()) === 0;
}
function removeDuplicates(personas: IPersonaProps[], possibleDupes: IPersonaProps[]) {
return personas.filter(persona => !listContainsPersona(persona, possibleDupes));
}
function listContainsPersona(persona: IPersonaProps, personas: IPersonaProps[]) {
if (!personas || !personas.length || personas.length === 0) {
return false;
}
return personas.filter(item => item.text === persona.text).length > 0;
}
function convertResultsToPromise(results: IPersonaProps[]): Promise<IPersonaProps[]> {
return new Promise<IPersonaProps[]>((resolve, reject) => setTimeout(() => resolve(results), 2000));
}
function getTextFromItem(persona: IPersonaProps): string {
return persona.text as string;
}
function validateInput(input: string): ValidationState {
if (input.indexOf('#') !== -1) {
return ValidationState.valid;
} else if (input.length > 1) {
return ValidationState.warning;
} else {
return ValidationState.invalid;
}
}
/**
* Takes in the picker input and modifies it in whichever way
* the caller wants, i.e. parsing entries copied from Outlook (sample
* input: "Aaron Reid <aaron>").
*
* #param input The text entered into the picker.
*/
function onInputChange(input: string): string {
const outlookRegEx = /<.*>/g;
const emailAddress = outlookRegEx.exec(input);
if (emailAddress && emailAddress[0]) {
return emailAddress[0].substring(1, emailAddress[0].length - 1);
}
return input;
}
Component which renders suggestion list have fixed width of 180px. Take a look at PeoplePickerItemSuggestion.styles.ts.
What you can do is to modify this class .ms-PeoplePicker-Persona:
.ms-PeoplePicker-Persona {
width: 260px; // Or what ever you want
}
UPDATE - Solution from comments
Change width trough styles property of PeoplePickerItemSuggestion Component
const onRenderSuggestionsItem = (personaProps, suggestionsProps) => (
<PeoplePickerItemSuggestion
personaProps={personaProps}
suggestionsProps={suggestionsProps}
styles={{ personaWrapper: { width: '100%' }}}
/>
);
<NormalPeoplePicker
onRenderSuggestionsItem={onRenderSuggestionsItem}
pickerCalloutProps={{ calloutWidth: 500 }}
...restProps
/>
Working Codepen example
For more information how to customize components read Component Styling.

What is the fastest way to create a union of many polygons in turfjs?

I have something like this but with large sets it's awfully slow:
let unionize = (triangles) => {
if(triangles.length == 0) {
return null
}
let ret = triangles[0].feature
triangles.forEach((t, index) => {
if(index > 0) {
ret = turf.union(t, t)
}
})
return ret
}
featureEach tends to be faster than a trivial array forEach although with more features the gain decreases.
<script src="https://cdn.jsdelivr.net/npm/#turf/turf#5.1.6/turf.min.js"></script>
<script>
const generateGrid = (cellSide = 100, units = "kilometers") => {
const bbox = [-95, 30, -85, 40];
return turf.triangleGrid(bbox, cellSide, {
units
});
}
const unionizeForEach = (triangles) => {
console.time('unionizeForEach');
if (triangles.length == 0) {
return null
}
let ret = triangles[0];
triangles.forEach((t, index) => {
if (index > 0) {
ret = turf.union(ret, t)
}
});
console.timeEnd('unionizeForEach');
return ret
}
const unionizeFeatureEach = (triangles) => {
console.time('unionizeFeatureEach');
if (triangles.features.length === 0) {
return null
}
let ret = triangles.features[0];
turf.featureEach(triangles, function (currentFeature, featureIndex) {
if (featureIndex > 0) {
ret = turf.union(ret, currentFeature)
}
});
console.timeEnd('unionizeFeatureEach');
return ret;
}
[100, 50, 10].map(cellSide => {
const triangleGrid = generateGrid(cellSide, 'kilometers');
console.info(`triangleGrid has ${triangleGrid.features.length} features`);
const union_foreach = unionizeForEach(triangleGrid.features);
const union_featureeach = unionizeFeatureEach(triangleGrid);
console.assert(JSON.stringify(union_foreach) === JSON.stringify(union_featureeach));
console.log('\n---\n');
})
</script>

How to modify an array before the render

I would like to change the value of my array to display the new array before the render.
I use componentWillMount to call my function firstly.
My function change the array in the function
import recipeData from '../Helpers/RecipeData'
componentWillMount(){
this._selectRicipe()
}
constructor(props) {
super(props)
this.state = {
myRecipeData: recipeData
}
}
_selectRicipe(){
for (let i = 0; i < recipeData.length; i++) {
for (let j = 0; j < this.props.listIngredients.length; j++) {
if (this.props.listIngredients[j].name == recipeData[i].type) {
newData = []
console.log(this.props.listIngredients[j].name)
newData = recipeData[i].name
this.setState({ myRecipeData: newData })
console.log("new RecipeData 1 : " + this.state.myRecipeData[i].name)
}
}
}
}
render() {
console.log("..New..recipe.. " + this.state.myRecipeData[0].name);
return (
<FlatList
data={this.state.myRecipeData}
keyExtractor={(item) => item.id.toString()}
renderItem={({ item }) => <RecipeDesc recipeData={item} />}
>
</FlatList>
)
}
Into my RecipDesc component I get the data in fact I can get the values of the first unmodified array
I tried to send the new array since an another view with
Maybe I need to use async operation ?
Thank you
I look at your code, I find you setState in a loop, it will affect your app performance. I modify it like below
constructor(props) {
super(props)
this.state = {
myRecipeData: recipeData
}
}
//please do it in the componentDidMount
componDidMount() {
this._selectRicipe()
}
_selectRicipe(){
let newData = [] // avoid to define a object in the loop repeately
for (let i = 0; i < recipeData.length; i++) {
for(let j = 0; j < this.props.listIngredients.length; j++){
if(this.props.listIngredients[j].name == recipeData[i].type){
console.log(this.props.listIngredients[j].name)
newData.push(recipeData[i].name)
// the flatlist neeed data is arry and not loop to
// setState
// this.setState({ myRecipeData: newData })
console.log("new RecipeData 1 :
"+this.state.myRecipeData[i].name)
}
}
}
this.setState({ myRecipeData: newData }) }
try this..
// put this in componentDidMount()
this.state = {
myRecipeData: recipeData,
newData:[],
}
and in your _selectRicipe,
_selectRicipe(){
for (let i = 0; i < this.state.myRecipeData.length; i++) {
for(let j = 0; j < this.props.listIngredients.length; j++){
if(this.props.listIngredients[j].name == recipeData[i].type){
console.log(this.props.listIngredients[j].name)
this.state.newData.push(recipeData[i].name);
console.log("new RecipeData 1 : "+this.state.myRecipeData[i].name)
}
}
}
// Outside of your for loop
this.setState({
newData:this.state.newData
});
}
and set new updated newData in your FlatList..
<FlatList
data={this.state.newData}
keyExtractor={(item,index) => index}
renderItem={({item}) => <RecipeDesc
recipeData={item}
/>}
>

React Native SectionList (title, data) - Search in the data field

I am trying to build Search function in SectionList. I have search inside the 'data' (second field) and not inside 'title' but I am not able to make it work.
My Data is about the Flat / resident details of an Apartment -
sectiondata =
[{"title":"GROUND FLOOR",
"data":[
{"id":"48","res_type":"owner","user_name":"Ashwani","flat_id":"1","flat_name":"001","floor_no":"GROUND FLOOR","floor_int":"0","signal_player_id":"aa","user_phone":"98855550"},
{"id":"49","res_type":"owner","user_name":"Rahul","flat_id":"2","flat_name":"002","floor_no":"GROUND FLOOR","floor_int":"0","signal_player_id":"aa","user_phone":"999999"}
]
}]
I am trying something like this but it is not working.
searchFilterFunction = (text) => {
let search = text.toLowerCase();
this.setState({
check: this.state.sectiondata.filter(
obj => obj.data['flat_name'].toLowerCase().includes(search))
});
}
How to filter data base on name? Please assist here.
Thanks.
You can try to search like this:
onChangeText(text) {
if (text.trim().length > 0) {
var temp = []
sectiondata.map((item) => {
var dataItem = {};
var brandData = [];
item.data.map((searchItem) => {
let flatName = searchItem.flat_name
if (flatName.match(text)) {
brandData.push(searchItem);
}
})
if (brandData.length > 0) {
} else {
return null;
}
dataItem.brandData = brandData;
temp.push(dataItem);
this.setState({
sectiondata: temp
})
})
} else {
this.setState({
sectiondata: this.state.tempData
})
}
}
searchFilterFunction(text) {
if( text == undefined || text == '') {
this.setState({
sectiondata: this.arrayholder
})
return;
}
if (text.trim().length > 0) {
var temp = []
this.state.sectiondata.map((item) => {
var dataItem = {};
var title = item.title;
var brandData = [];
item.data.map((searchItem) => {
let flatName = searchItem.flat_name
if (flatName.match(text)) {
brandData.push(searchItem);
}
})
if (brandData.length > 0) {
} else {
return null;
}
dataItem.title = title;
dataItem.data = brandData;
temp.push(dataItem);
this.setState({
sectiondata: temp
})
})