add user input data to consts in React app - javascript

I have an app.js file in a trello clone.
Toy data is stored,representing posts.
const book1 = [
{id: uuid(), content: 'reflections'}
];
const book2 = [
{id: uuid(), content: 'arising'},
]
a single constant pulls the toy data into columns for the trello clone.
const clusterColumns =
{
[uuid()]: {
name: 'Book 1',
items: book1
},
[uuid()]: {
name: 'Book 2',
items: book2
},
};
The data is hard coded into these consts. Id like to add a user input to the page that, so that users can add their own items to consts for the trello clone.
the clusterColumns const is added to a third const that simply cleans up the data as i move it around on the board:
const onDragEnd = (result, columns, setColumns ) => {
if(!result.destination ) return;
const {source, destination} = result;
if (source.droppableId!==destination.droppableId) {
const sourceColumn = columns[source.droppableId];
const destColumn = columns[destination.droppableId];
const sourceItems = [...sourceColumn.items];
const destItems = [...destColumn.items];
const [removed] = sourceItems.splice(source.index, 1);
destItems.splice(destination.index, 0, removed);
setColumns({
...columns,
[source.droppableId]:{
...sourceColumn,
items: sourceItems,
},
[destination.droppableId]:{
...destColumn,
items: destItems
}
})
}
else {
const column = columns[source.droppableId];
const copiedItems = [...column.items];
const [removed] = copiedItems.splice(source.index, 1);
copiedItems.splice(destination.index, 0, removed)
setColumns({
...columns,
[source.droppableId]: {
...column,
items: copiedItems
}
})
}
};
a main bit of the app.js file is a nested function that builds drag and drop elements with some style, pulling in the toy data
function App() {
const [columns, setColumns] = useState(clusterColumns);
return (
<div>
<div style={{display: 'flex', justifyContent: 'left', height: '95%', position: "relative",
top: 5, left: 90, opacity: '27%'}}>
<DragDropContext onDragEnd={result => onDragEnd(result, columns, setColumns)}>
{Object.entries(columns).map(([id, column]) => {
return (
<div style={{display: 'flex', flexDirection: 'column', alignItems:'center',
fontFamily: 'Montez, sans-serif', color: '#913aff', fontSize: 27, padding:5, borderRadius: '19px',
}}><h2 style={{fontSize:(19*3), height: 45}}>{column.name}</h2>
<h2 style={{fontSize:(19*3), height: 45, top:'9px', position:'absolute', opacity:'60%', color:'#ffa0f9'}}>{column.name}</h2>
<div style={{margin: 2}}>
<Droppable droppableId={id} key={id} >
{(provided, snapshot) => {
return (
<div {...provided.droppableProps}
ref={provided.innerRef}
style={{
padding: 9,
width: 190,
minHeight: 9,
opacity: '95%',
borderRadius: '9px',
background: 'linear-gradient(to right bottom, rgba(196, 181, 255, 1), rgba(132,47,0,0.27)'}} >
{column.items.map((item, index) => {
return (
<Draggable key={item.id} draggableId={item.id} index={index}>
{(provided, snapshot) => {
return (
<div
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
style={{
opacity: '95%',
userSelect: 'none',
padding: 19,
margin: '0px 0px 3px 0px',
backgroundColor: snapshot.isDragging ? '#54ffff':'#b3f542',
background: 'linear-gradient(to right bottom, rgba(84, 255, 255, 0.63), rgba(179, 245, 66, 0.81)',
color: 'rgb(115,38,0)' ,
fontFamily: 'Montez',
fontSize: 36,
borderRadius: '9px',
...provided.draggableProps.style
}}>
{item.content}
</div>
)
}}
</Draggable>
)
}
)}
{provided.placeholder}
</div>
)
}}
</Droppable>
</div>
</div>
)
})}
</DragDropContext>
</div>
</div>
);
}
I've tried adding another class:
class Cell extends React.Component {
render() {
return (
<form>
<input
type="text" style={{
display:'flex',
position:'relative',
top: '-360px',
right:'95px',
fontFamily: "VT323",
width:'144px',
fontSize:'36px',
color: 'rgb(115,38,0)',
opacity:'60%',
borderRadius: '9px',
height: '45px',
background: 'radial-gradient(rgba(196, 181, 255, .9), rgba(168,255,0,0.19)',
borderColor: 'rgba(255,255,255,0)'
}}
/>
</form>
);
}
}
But it is a simple user form. I'd like to have the data entered be added to those consts at the top of the program.

Related

How we can give auto height to FlatList based on its list items content in React Native

I am using FlatList in my component which is working fine. All is wanted is that my entire screen should have an automatic height to it and FlatList contents never does out of the screen height.
Also, the height of FlatList should be changed based on content/items in it rather than giving any fixed height.
How I can be acheived both cases like automatic screen height and auto height of FlatList content?
Code:
import React, { useState, useEffect } from 'react';
import {
View,
StyleSheet,
useWindowDimensions,
Text,
FlatList,
SafeAreaView,
TouchableOpacity,
} from 'react-native';
import { LinearGradient as LinearGradientView } from 'expo-linear-gradient';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { ActivityIndicator, ThemeProvider } from 'react-native-paper';
import { ScrollView } from 'react-native-gesture-handler';
import { useIsFocused, useNavigation } from '#react-navigation/native';
import Svg, { Path } from 'react-native-svg';
import { BASE_GRADIENT_HEAVY } from '../rooms/Background';
import { useResolution } from '../browse/useResolution';
import { OnboardingNavigationProp } from '../navigation/LinkingConfiguration';
import { LIGHT_THEME } from '../Theme';
import { OnboardingBack } from './OnboardingBack';
import {
useOnboardingYearsOfExperiencePage,
useOnboardingYearsOfExperienceSubmit,
} from './useOnboardingYearsOfExperiencePage';
export function OnboardingYearsOfExperience({ route }: { route?: any }) {
const { height } = useWindowDimensions();
const { top: safeAreaTop } = useSafeAreaInsets();
const [selectedId, setSelectedId] = useState<{ id: string }>();
const [role_id, setRoleId] = useState<number>();
const { navigate } =
useNavigation<OnboardingNavigationProp<'OnboardingConfirmAllDetails'>>();
const parentUrl = route?.params.result.onboarding._links;
const initialUrl = parentUrl.onboarding_years_of_experience.href;
const onboardingUrl = parentUrl.self.href;
useEffect(() => {
setRoleId(route?.params.role_id);
}, []);
const isFocused = useIsFocused();
const { contentType } = useResolution();
const {
data: result,
isLoading,
error,
} = useOnboardingYearsOfExperiencePage(initialUrl, contentType, role_id, {
enabled: isFocused,
notifyOnChangeProps: ['data', 'isLoading', 'error'],
});
const {
mutateAsync: updateYearsOfExperience,
isLoading: isUpdatingYearsOfExperience,
error: yearsOfExperienceUpdateError,
} = useOnboardingYearsOfExperienceSubmit(onboardingUrl);
const Arrow = ({ style }: { style: object }) => {
return (
<Svg width="7" height="11" viewBox="0 0 7 11" fill="none" style={style}>
<Path
d="M6.28711 5.53931C6.28711 5.31649 6.19783 5.12476 6.02452 4.95376L1.9911 1.07251C1.85455 0.937781 1.68649 0.865234 1.48692 0.865234C1.07728 0.865234 0.751664 1.18651 0.751664 1.58552C0.751664 1.78243 0.830441 1.96898 0.977493 2.11407L4.54875 5.53413L0.977492 8.95937C0.835692 9.10446 0.751663 9.28583 0.751662 9.48792C0.751662 9.88693 1.07728 10.2082 1.48692 10.2082C1.68649 10.2082 1.85455 10.1357 1.99635 10.0009L6.02452 6.11968C6.20308 5.93832 6.28711 5.75695 6.28711 5.53931Z"
fill="#4D4D4D"
/>
</Svg>
);
};
const Item = ({
item,
onPress,
}: {
item?: { id: string; title: string };
onPress: () => void;
}) => (
<TouchableOpacity onPress={onPress}>
<Text
style={{
color: '#4D4D4D',
fontFamily: 'Inter_400Regular',
fontStyle: 'normal',
fontWeight: '400',
fontSize: 16,
lineHeight: 32,
padding: 3,
margin: 2,
}}
>
{item?.title}
</Text>
</TouchableOpacity>
);
const renderItem = ({ item }: { item: { id: string; title: string } }) => {
return (
<React.Fragment>
<View
style={{
flexDirection: 'row',
justifyContent: 'space-between',
borderRadius: 5,
backgroundColor:
selectedId?.id === item?.id ? '#F2F2F2' : 'transparent',
}}
>
<View style={{ width: '90%' }}>
<Item
item={item}
onPress={() => {
setSelectedId({ id: item.id });
updateYearsOfExperience({ id: item.id, role_id })
.then((result) => {
navigate('Onboarding', {
screen: 'OnboardingConfirmAllDetails',
params: { result },
});
})
.catch(() => {});
}}
/>
</View>
<View style={{ width: '10%' }}>
<Arrow style={{ position: 'absolute', top: 16, right: 10 }} />
</View>
</View>
</React.Fragment>
);
};
return (
<ThemeProvider theme={LIGHT_THEME}>
<View style={{ height: safeAreaTop }} />
<View style={styles.topHeader}>
<LinearGradientView
{...BASE_GRADIENT_HEAVY}
style={[styles.gradiantStyle]}
/>
</View>
<View style={styles.innerContainer}>
<ScrollView
contentContainerStyle={{
marginHorizontal: 'auto',
alignSelf: 'center',
width: '100%',
backgroundColor: '#ffffff',
height: '100%',
}}
>
<OnboardingBack
style={{
left: -10,
}}
/>
<Text style={styles.topHeadline}>
How many years of experience do you have?
</Text>
<Text style={styles.middleHeadline}>
Jump-start the conversation by sharing your years of experience
within healthcare.
</Text>
{isLoading || isUpdatingYearsOfExperience ? (
<ActivityIndicator size="large" />
) : (
<SafeAreaView>
<FlatList
contentContainerStyle={{ flexGrow: 1 }}
data={Object.values(
result!['years_of_experiences']['years_of_experiences_list']
)}
renderItem={renderItem}
keyExtractor={(item) => item.id}
extraData={selectedId}
style={{
borderWidth: 1,
borderStyle: 'solid',
borderColor: '#D7D7D7',
borderRadius: 5,
padding: 12,
height: '27%',
}}
ListEmptyComponent={
<View>
<Text>No data found</Text>
</View>
}
/>
</SafeAreaView>
)}
</ScrollView>
</View>
</ThemeProvider>
);
}
const styles = StyleSheet.create({
innerContainer: {
display: 'flex',
position: 'relative',
backgroundColor: 'white',
padding: 18,
},
topHeader: {
backgroundColor: '#e5dede',
padding: 0,
width: '100%',
},
topHeadline: {
fontSize: 24,
fontFamily: 'CircularStd_Medium',
fontStyle: 'normal',
fontWeight: '500',
color: '#222222',
marginTop: 40.6,
marginBottom: 14.6,
display: 'flex',
alignItems: 'center',
lineHeight: 32,
},
middleHeadline: {
fontSize: 16,
fontFamily: 'Inter_400Regular',
fontStyle: 'normal',
fontWeight: '400',
lineHeight: 24,
color: '#4D4D4D',
marginBottom: 30,
},
gradiantStyle: {
width: 248.4,
height: 4.71,
},
});
add the following style to your flatList =>
style={{maxHeight:'what ever you want',flexGrow:0}}

Struggling to update button style on press

In our code we want the individual button to update style on press and to be able to basically have it update state to where we know it is pressed and can send that it was taken to our database when the submit button is pressed. We have the submit button working but we can't seem to update the seat buttons when we press them to change their color. Instead, we have to wait and reload the page before it changes anything. Here is the code below.
export const OrderScreen = ({ navigation }) => {
const [counter, setCounter] = useState(0);
LogBox.ignoreLogs(['Setting a timer']);
const [order, setOrder] = useState('Unknown');
const COL = 5;
const [data, setData] = useState([]);
const [seats, setSeats] = useState([]);
const updateSeat = async (taken,rowNum,seat) => {
const DocRef = doc(db, "Theaters/Seating/Theater1", rowNum);
await updateDoc(DocRef, {
[seat] : taken
});
};
var ListofOrders = [];
function recordOrder(name,qty){
console.log(name, qty);
ListofOrders = ListofOrders.filter(function( element ) {
return element !== undefined;
});
if(ListofOrders.length != 0){
for (let i = 0; i < ListofOrders.length; i++ ){
//console.log(ListofOrders[i][0]);
if(ListofOrders[i][0] == name){
delete ListofOrders[i];
}
}
}
var array = [name,qty];
ListofOrders.push(array);
//console.log(ListofOrders);
};
const SubmitOrder = async() =>{
for (let i = 0; i < ListofOrders.length; i++ ){
const q = query(collection(db, 'Inventory'), where("name" , "==" , ListofOrders[i][0]));
//console.log(ListofOrders[i][0]);
const querySnapshot = getDocs(q);
querySnapshot.forEach((doc) => {
console.log(doc.id);
docid = doc.id;
});
const dbRef = doc(db, 'Inventory', docid);
updateDoc(dbRef, {
qty: ListofOrders[i][1]
});
}
console.log("successful");
};
function seatTaken(position){
switch(position){
case true: return(styles.seatButton); break;
case false: return(styles.seatButtonTaken); break;
}
};
//function handleClick (){
// setState('buttontaken')
// }
useEffect(() => {
const getInventory = async () => {
const inventorySnapshot = await getDocs(collection(db, "Inventory"));
const inventoryList = inventorySnapshot.docs.map((doc) => doc.data());
setData(inventoryList);
// console.log(inventoryList);
};
getInventory();
const getSeating = async () => {
const seatSnapshot = await getDocs(collection(db, "Theaters/Seating/Theater1"));
const seatList = seatSnapshot.docs.map((doc) => doc.data());
setSeats(seatList);
//console.log(seatList);
};
getSeating();
}, [])
return (
<View style={styles.container}>
<ScrollView>
<Text style={styles.screenTitle}>New Order</Text>
{/* Theater Selection */}
<Text style ={styles.text}> Ticket Order</Text>
<Picker
selectedValue={order}
onValueChange={(value, index) => setOrder(value)}
mode="dropdown" // Android only
style={styles.picker}
>
<Picker.Item label="Please select your Order" value="Unknown" />
<Picker.Item label="Theater 1 5PM" value="Theater 1" />
<Picker.Item label="Theater 2 5PM" value="Theater 2" />
</Picker>
{/* Seat Animation */}
{seats.map((seats,index1,index2,index3) =>(
<React.Fragment>
<View style = {styles.containerseats}>
<Text style = {styles.itemText}> Row {index1 + 1} </Text>
<Button key = {seats} style = {seatTaken(seats.A)} onPress = {() => updateSeat(false, 'Row' + (index1 + 1),'A')}/>
<Button key = {index1} style = {seatTaken(seats.B)} onPress = {() => updateSeat(false, 'Row' + (index1 + 1),'B')}/>
<Button key = {index2} style = {seatTaken(seats.C)} onPress = {() => updateSeat(false, 'Row' + (index1 + 1),'C')}/>
<Button key = {index3} style = {seatTaken(seats.D)} onPress = {() => updateSeat(false, 'Row' + (index1 + 1),'D')} />
</View>
</React.Fragment>
))}
{/* Food order */}
{data.map((data,qty) =>(
<React.Fragment>
<View style = {styles.parent}>
<View style = {styles.block}>
<Text key = {data} style = {styles.itemText}> {data.name}</Text>
</View>
<View style = {styles.block} >
<Counter start = {parseInt(0)} max = {parseInt(data.qty)} onChange={(len, type) => {
console.log(len, type);
qty = len;
recordOrder(data.name,qty);
}} />
</View>
</View>
</React.Fragment>
))}
{/* Buttons */}
<Button style={styles.buttonsubmit} onPress = {() => SubmitOrder()}>
<Text style={styles.buttonText}>Submit Order</Text>
</Button>
<Button style={styles.borderlessButtonContainer} borderless
title={'Cancel Order'}
onPress = {() => navigation.navigate('CustomerHomeScreen')} />
</ScrollView>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'black',
paddingHorizontal: 12,
alignItems: 'center'
},
screenTitle: {
fontSize: 18,
fontWeight: '700',
color: Colors.orange,
paddingTop: 10,
textAlign: 'center',
},
text: {
fontSize: 18,
fontWeight: '700',
color: Colors.orange,
paddingTop: 10,
textAlign: 'center',
},
button: {
width: '10%',
height: 18,
marginTop: 8,
alignItems: 'center',
backgroundColor: Colors.orange,
padding: 10,
borderRadius: 8,
marginRight:8
},
buttonsubmit: {
width: '50%',
justifyContent: 'center',
alignItems: 'center',
alignSelf: 'center',
marginTop: 8,
backgroundColor: Colors.orange,
padding: 10,
borderRadius: 8,
},
buttontaken: {
width: '10%',
height: 18,
marginTop: 8,
backgroundColor: Colors.black,
borderColor: Colors.white,
padding: 10,
borderWidth:2,
borderRadius:8,
marginRight:8,
alignItems: 'center',
justifyContent: 'center',
},
buttonText: {
fontSize: 20,
color: Colors.white,
fontWeight: '700',
},
borderlessButtonContainer: {
marginTop: 16,
alignItems: 'center',
},
picker: {
marginVertical: 30,
width: 300,
padding: 10,
borderWidth: 5,
color: Colors.black,
backgroundColor: 'white',
},
containerseats: {
flexDirection: 'row',
flex: 1,
alignContent: 'space-around',
padding: 5
},
seatButton: {
width: '10%',
height: 18,
marginTop: 8,
backgroundColor: Colors.orange,
padding: 10,
borderRadius: 8,
marginRight:8
},
seatButtonTaken: {
width: '10%',
height: 18,
marginTop: 8,
backgroundColor: Colors.black,
borderColor: Colors.white,
padding: 9,
borderWidth:2,
borderRadius:8,
marginRight:8,
alignItems: 'center',
justifyContent: 'flex-end',
},
itemText: {
fontSize: 20,
fontWeight: '500',
color: '#ff9361',
},
parent: {
flexDirection: "row",
},
block: {
flex: 3,
margin: 6,
},
});
It is pulling from a firebase database and looks like the image below. I would like the button I press to immediately update the style of that button to seatbuttontaken style instead of seatbutton. Please let me know if there's any other helpful information I can provide.

Update name of selected node from sidebar in React Flow

I am very new to react.js and JavaScript, so apologies in advance.
I am trying to make a very concise diagramming tool in my webpage, where the user can create their own use case diagram.
I am looking at these examples:
https://reactflow.dev/examples/drag-and-drop/
https://reactflow.dev/examples/update-node/
I got the drag and drop to work, but am having a hard time applying the update node feature. My final goal is to let the user select a node, and update its name via input at the sidebar.
I started with adding const onElementClick = (event, element) => event.dataTransfer.getData("label"); to the main file to get the label from the sidebar, and am trying to send back the changed label by adding the block code below.
<label> label: </label>
<input value={nodeName} onChange={(evt) => setNodeName(evt.target.value)} />
Because their example on https://reactflow.dev/examples/update-node/ has everything in a single file, and am not able to update the node's name with selection, I am just a bit unsure how to proceed from here.
Any help would be sincerely appreciated, as a beginner in react.
Again, apologies and thanks in advance!
main.js
import Sidebar from "./Sidebar";
const initialElements = [
{
id: "1",
type: "input",
data: { label: "User" },
position: { x: 300, y: 150 },
},
{
id: "2",
type: "default",
data: { label: "Use Case" },
position: { x: 700, y: 250 },
},
{
id: "3",
type: "output",
data: { label: "Database" },
position: { x: 1100, y: 350 },
},
];
let id = 0;
const getId = () => `dndnode_${id++}`;
export const Tester = () => {
const reactFlowWrapper = useRef(null);
const [reactFlowInstance, setReactFlowInstance] = useState(null);
const [elements, setElements] = useState(initialElements);
const [nodeName, setNodeName] = useState("Node 1");
const [nodeBg, setNodeBg] = useState("#eee");
const [nodeHidden, setNodeHidden] = useState(false);
const onElementClick = (event, element) => event.dataTransfer.getData("click", element);
const onConnect = (params) => setElements((els) => addEdge(params, els));
const onElementsRemove = (elementsToRemove) =>
setElements((els) => removeElements(elementsToRemove, els));
const onLoad = (_reactFlowInstance) => setReactFlowInstance(_reactFlowInstance);
const onDragOver = (event) => {
event.preventDefault();
event.dataTransfer.dropEffect = "move";
};
const onDrop = (event) => {
event.preventDefault();
const reactFlowBounds = reactFlowWrapper.current.getBoundingClientRect();
const type = event.dataTransfer.getData("application/reactflow");
const label = event.dataTransfer.getData("label");
const position = reactFlowInstance.project({
x: event.clientX - reactFlowBounds.left,
y: event.clientY - reactFlowBounds.top,
});
const newNode = {
id: getId(),
type,
position,
data: { label: label },
};
setElements((es) => es.concat(newNode));
};
return (
<div className="dndflow">
<ReactFlowProvider>
<Box
className="reactflow-wrapper"
ref={reactFlowWrapper}
style={{ height: 600 }}
sx={{ display: "flex", justifyContent: "space-between", justifyContent: "center" }}
>
<ReactFlow
elements={elements}
onConnect={onConnect}
onElementsRemove={onElementsRemove}
onLoad={onLoad}
onDrop={onDrop}
onDragOver={onDragOver}
onElementClick={onElementClick}
>
<Controls />
<MiniMap />
<Background variant="lines" size={1.5} gap={20} color="#eee" />
</ReactFlow>
<Box sx={{ ml: 10 }}>
<Sidebar />
</Box>
</Box>
</ReactFlowProvider>
</div>
);
};
Sidebar.js
export default () => {
const onDragStart = (event, nodeType, label) => {
event.dataTransfer.setData("application/reactflow", nodeType);
event.dataTransfer.setData("label", label);
event.dataTransfer.effectAllowed = "move";
};
const changeNodeName = (event, nodetype, label) => {
//event.dataTransfer.getData()
const [nodeName, setNodeName] = useState("Node 1");
};
return (
<aside>
<Box
sx={{
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
}}
>
<div className="description">Drag nodes to the pane.</div>
<Box
className="dndnode input"
onDragStart={(event) => onDragStart(event, "input", "User")}
draggable
sx={{
mt: 2,
border: 1,
borderColor: "blue",
borderRadius: 0.5,
width: 200,
height: 50,
textAlign: "center",
py: 1.4,
"&:hover": {
opacity: 0.5,
},
}}
>
User
</Box>
<Box
className="dndnode"
onDragStart={(event) => onDragStart(event, "default", "Use Case")}
draggable
sx={{
mt: 2,
border: 0.5,
borderColor: "black",
borderRadius: 0.5,
width: 200,
height: 50,
textAlign: "center",
py: 1.4,
"&:hover": {
opacity: 0.5,
},
}}
>
Use Case
</Box>
<Box
className="dndnode output"
onDragStart={(event) => onDragStart(event, "output", "Database")}
draggable
sx={{
mt: 2,
border: 0.5,
borderColor: "red",
borderRadius: 0.5,
width: 200,
height: 50,
textAlign: "center",
py: 1.4,
"&:hover": {
opacity: 0.5,
},
}}
>
Database
</Box>
</Box>
</aside>
);
};
I get the same problem as you, but after a while, I solve this problem after reading it many times in the docs https://reactflow.dev/docs/api/react-flow-props/,
you can use onNodeClick(event: React.MouseEvent, node: Node) and set a state like show-sidebar that will change every time u click on the nodes set-Show-Sidebar( !show-sidebar), so when it gets true u send the node-id to Sidebar change it and receiver it, change it with onChange function then update nodes with
nodes.map((node)=>{node.id === id ? {...node, label:newName } : node})

Rotate label - Material UI button

I've got a button like this (material-ui):
//theme.js
export const XButtonTop = withStyles({
root: {
borderColor: medium_col,
borderRadius: 1,
borderTopLeftRadius: 16,
borderTopRightRadius: 16,
height: 28
},
label: {
textTransform: "uppercase",
fontSize: "10px"
}
})(Button);
//App.js
import {
XButtonTop
} from "../theme";
const Selector = state => {
return (
<div>
<XButtonTop fullWidth size="small" disableElevation>
)
</XButtonTop>
</div>
)
}
I need to rotate the label (90 degrees).
Can someone help me please? Thanks
label: {
textTransform: 'capitalize',
transform: 'rotate(-90deg)',
}
Then you may want to change the height of the button too. Something like this for the root:
height: 120,
width: 30

React-native wait before doing some task

Hey i am trying to render some cards like tinder so it works but only when i use data that is already in the project, when i try to use data that i get from firebase is don't show up cause it render the cards before getting the data from firebase so how can i do it ?
I tried with this.setstate but no changes
i get the data like this and set it in the array
componentWillMount() {
Users = [
]
var query = firebase.database().ref("users").orderByKey();
query.once("value")
.then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
// key will be "ada" the first time and "alan" the second time
var key = childSnapshot.key;
// childData will be the actual contents of the child
var childData = childSnapshot.val();
Users.push({ id: key, uri: {uri: childData.photo} })
});
});
}
renderUsers = () => {
console.log(Users)
return Users.map((item, i) => {
if (i < this.state.currentIndex) {
return null
}
else if (i == this.state.currentIndex) {
return (
<Animated.View
{...this.PanResponder.panHandlers}
key={item.id} style={[this.rotateAndTranslate, { height: SCREEN_HEIGHT - 120, width: SCREEN_WIDTH, padding: 10, position: 'absolute' }]}>
<Animated.View style={{ opacity: this.likeOpacity, transform: [{ rotate: '-30deg' }], position: 'absolute', top: 50, left: 40, zIndex: 1000 }}>
<Text style={{ borderWidth: 1, borderColor: 'green', color: 'green', fontSize: 32, fontWeight: '800', padding: 10 }}>LIKE</Text>
</Animated.View>
<Animated.View style={{ opacity: this.dislikeOpacity, transform: [{ rotate: '30deg' }], position: 'absolute', top: 50, right: 40, zIndex: 1000 }}>
<Text style={{ borderWidth: 1, borderColor: 'red', color: 'red', fontSize: 32, fontWeight: '800', padding: 10 }}>NOPE</Text>
</Animated.View>
<Image
style={{ flex: 1, height: null, width: null, resizeMode: 'cover', borderRadius: 20 }}
source={item.uri} />
<Text>{item.id}</Text>
</Animated.View>
)
}
else {
return (
<Animated.View
key={item.id} style={[{
opacity: this.nextCardOpacity,
transform: [{ scale: this.nextCardScale }],
height: SCREEN_HEIGHT - 120, width: SCREEN_WIDTH, padding: 10, position: 'absolute'
}]}>
<Animated.View style={{ opacity: 0, transform: [{ rotate: '-30deg' }], position: 'absolute', top: 50, left: 40, zIndex: 1000 }}>
<Text style={{ borderWidth: 1, borderColor: 'green', color: 'green', fontSize: 32, fontWeight: '800', padding: 10 }}>LIKE</Text>
</Animated.View>
<Animated.View style={{ opacity: 0, transform: [{ rotate: '30deg' }], position: 'absolute', top: 50, right: 40, zIndex: 1000 }}>
<Text style={{ borderWidth: 1, borderColor: 'red', color: 'red', fontSize: 32, fontWeight: '800', padding: 10 }}>NOPE</Text>
</Animated.View>
<Image
style={{ flex: 1, height: null, width: null, resizeMode: 'cover', borderRadius: 20 }}
source={item.uri} />
<Text>{item.id}</Text>
</Animated.View>
)
}
}).reverse()
}
this function render the cards
Any async operation takes time until it resolves ... if you want to use setState to solve your issue ... here's how:
state = {
users: null,
};
componentDidMount() {
users = [];
const query = firebase
.database()
.ref('users')
.orderByKey();
query.once('value').then((snapshot) => {
// Here you users are available:
this.setState({ users });
});
}
render() {
const { users } = this.state;
if (!users) return null;
return users.map(...);
}
componentWillMount should not be used anymore

Categories