How to display fetch data inside the table - javascript

How to get fetch data inside the react-native table here ?
When i tried to fetch data, the table display empty with this codes, so where and what to do for get the data from API and display in the table in react native.
getData() {
fetch('https://www.lampmonitor.com/lampmonitor/api/auth/web/lampControls?projectId=595&pageSize=50')
.then(responce => responce.json())
.then(data => {
this.setState({
tableData: data
});
});
}
render() {
const state = this.state;
const { tableData } = state;
return (
<View style={styles.container}>
<ScrollView horizontal={true}>
<View>
<Table borderStyle={{borderWidth: 1, borderColor: '#C1C0B9'}}>
<Row
data={state.tableHead}
widthArr={state.widthArr}
style={styles.header}
textStyle={styles.text}
/>
</Table>
<ScrollView style={styles.dataWrapper}>
<Table borderStyle={{borderWidth: 1, borderColor: '#C1C0B9'}}>
{tableData.map((rowData, index) => (
<Rows
key={index}
data={rowData}
widthArr={state.widthArr}
style={[
styles.row,
index % 2 && {backgroundColor: '#F7F6E7'},
]}
textStyle={styles.text}
/>
))}
</Table>
</ScrollView>
</View>
</ScrollView>
</View>
);
}

This is an example of how to do it using React hooks.
https://reactjs.org/docs/hooks-state.html
You have many errors and I think you need to brush up on the differences between Class components and Functional components using React Hooks.
import React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
export default TableComponent;
import React, { useState, useEffect } from 'react';
const TableComponent = () => {
const [tableData, setTableData] = useState({});
useEffect(() => {
async function getData() {
fetch('https://www.lampmonitor.com/lampmonitor/api/auth/web/lampControls?projectId=595&pageSize=50')
.then(responce => responce.json())
.then(data => {
setTableData({data});
});
}
getData();
}, []);
return (
<View style={styles.container}>
<ScrollView horizontal={true}>
<View>
<Table borderStyle={{borderWidth: 1, borderColor: '#C1C0B9'}}>
<Row
data={tableData.tableHead}
widthArr={tableData.widthArr}
style={styles.header}
textStyle={styles.text}
/>
</Table>
<ScrollView style={styles.dataWrapper}>
<Table borderStyle={{borderWidth: 1, borderColor: '#C1C0B9'}}>
{tableData.map((rowData, index) => (
<Rows
key={index}
data={rowData}
widthArr={tableData.widthArr}
style={[
styles.row,
index % 2 && {backgroundColor: '#F7F6E7'},
]}
textStyle={styles.text}
/>
))}
</Table>
</ScrollView>
</View>
</ScrollView>
</View>
);
}

Related

React native: Update value of object in array in state

I have a component which changes the state when checkbox is checked and the data needs to be updated of the object in the array.
The component state looks something like this
{
key:1,
todo:"Something",
isChecked:false
}
i have 3 files:
AddTodo.js Which passes state & setState to an component TodoList which passes it the subcomponent TodoItem.
I am unable to update the state from TodoItem , I need to implement a function that finds the object from array and updates its isChecked state.
AddTodo.js
function AddTodo() {
const [state, setState] = useState(false);
const [todos, addTodos] = useState([]);
var keys = (todos || []).length;
return (
<View style={styles.container}>
<Modal
animationType="slide"
transparent={true}
visible={state}
statusBarTranslucent={true}
>
<View style={styles.itemsContainer}>
<GetInfoDialog
state={state}
stateChange={setState}
addItem={addTodos}
numKeys={keys}
/>
</View>
</Modal>
{(todos || []).length > 0 ? (
<TodoList data={todos} updateState={addTodos} />
) : null}
<TouchableOpacity
style={styles.btn}
onPress={() => {
setState(true);
}}
>
<Text style={styles.text}>Add New</Text>
</TouchableOpacity>
</View>
);
}
TodoList.js
function TodoList(props) {
return (
<View style={styles.todoList}>
<FlatList
data={props.data}
renderItem={({ item }) => {
console.log(item);
return (
<TodoItem
list={props.data}
itemKey={item.key}
todo={item.todo}
isChecked={item.isChecked}
updateState={props.updateState}
/>
);
}}
backgroundColor={"#000000"}
alignItems={"center"}
justifyContent={"space-between"}
/>
</View>
);
}
TodoItem.js
function TodoItem(props) {
const [checked, setCheck] = useState(props.isChecked);
return (
<View style={styles.todoItem}>
<Checkbox
value={checked}
onValueChange={() => {
setCheck(!checked);
}}
style={styles.checkbox}
/>
<Text style={styles.text}>{props.todo}</Text>
</View>
);
}
renderItem={({ item, index }) => {
console.log(item);
return (
<TodoItem
list={props.data}
itemKey={item.key}
todo={item.todo}
isChecked={item.isChecked}
updateState={props.updateState}
setChecked={(value)=>{
let updatedList = [...yourTodosList]
updatedlist[index].isChecked=value
setTodos(updatedList)
}}
/>
);
}}
and in your todo item
onValueChange={(value) => {
props.setChecked(value);
}}
i also don't think that you need an is checked state in your todo component since you are passing that through props (so delete const [checked, setCheck] = useState(props.isChecked) line and just use the value you are getting from props.isChecked)
didn't pay much attention to your variable names but this should put you on the right track
as per React Native Hooks you have to call
useEffect(() => {
setCheck(checked);
}, [checked]) // now this listens to changes in contact
in TodoItem.tsx

react native: Displays a single table with the data

In my code I expect to get only one table with the data but what happens is that I get a lot of tables with the same data and it is not clear to me why.
Lots of tables are accepted and I should get only one table.
I would be happy to help with this
export const ActionModal = (props: any) => {
const { pointsData } = useGetPoints();
const [tableHead] = useState(['אזור', 'אתר', 'נ`ק איסוף', 'מיקום']);
const [tableData, setTableData] = useState([]);
const arrangeData = () => {
let rows: any[] = [];
pointsData.forEach(e => {
let row = [e.area, e.site, e.gatheringPoint, e.location];
rows.push(row);
});
setTableData(rows);
}
useEffect(() => {
arrangeData();
}, []);
const renderItem = ({ item }: any) => (
<View style={styles.item}>
<View style={styles.tableView}>
<Table borderStyle={{ borderWidth: 2, borderColor: '#c8e1ff' }}>
<Row data={tableHead} style={styles.head} textStyle={styles.text} />
<Rows data={tableData} textStyle={styles.text} />
</Table>
</View>
<Text style={{ fontSize: 18 }}>{item.area}, {item.site}, {item.gatheringPoint}, {item.location}</Text>
</View>
)
return (
<Modal
animationType={'slide'}
transparent={false}
visible={props.actionModalVisible}
onRequestClose={() => {
console.log('Modal has been closed.');
}}>
<View style={styles.modal}>
{pointsData.length ?
<FlatList
data={pointsData}
renderItem={renderItem}
keyExtractor={item => item.gatheringID}
/> :
<ActivityIndicator size="large" />}
</View>
<Button
title="סגור"
onPress={props.onClose}
/>
</Modal>
);
};
Table are rendered inside a item of flatlist
the function renderItem will repeate like a number of row of you array , this why you get lot of table ..
to fix this you need to pull out of flatlist like this to rendering table once time :
export const ActionModal = (props: any) => {
const { pointsData } = useGetPoints();
const [tableHead] = useState(['אזור', 'אתר', 'נ`ק איסוף', 'מיקום']);
const [tableData, setTableData] = useState([]);
const arrangeData = () => {
let rows: any[] = [];
pointsData.forEach(e => {
let row = [e.area, e.site, e.gatheringPoint, e.location];
rows.push(row);
});
setTableData(rows);
}
useEffect(() => {
arrangeData();
}, []);
const renderItem = ({ item }: any) => (
<Text style={{ fontSize: 18 }}>{item.area}, {item.site}, {item.gatheringPoint}, {item.location}</Text>
)
return (
<Modal
animationType={'slide'}
transparent={false}
visible={props.actionModalVisible}
onRequestClose={() => {
console.log('Modal has been closed.');
}}>
<View style={styles.modal}>
{pointsData.length ?
<View style={styles.item}>
<View style={styles.tableView}>
<Table borderStyle={{ borderWidth: 2, borderColor: '#c8e1ff' }}>
<Row data={tableHead} style={styles.head} textStyle={styles.text} />
<Rows data={tableData} textStyle={styles.text} />
</Table>
</View>
<FlatList
data={pointsData}
renderItem={renderItem}
keyExtractor={item => item.gatheringID}
/>
</View>:
<ActivityIndicator size="large" />}
</View>
<Button
title="סגור"
onPress={props.onClose}
/>
</Modal>
);
};

TypeError: undefined is not a function (near '...data.map...')

I updated my code thanks to your help.
When I launch the app with Expo, the opening works but I lost my scan icon which does not appear in my screen.
This icon appeared previously.
The idea is to scan some barcodes in order to display relevant data stemming from products.
Here is my new code:
import React, { useState, useEffect } from "react";
import {
StyleSheet,
Text,
View,
FlatList,
Button,
AsyncStorage,
} from "react-native";
import { useNavigation } from "#react-navigation/core";
import { TouchableOpacity } from "react-native-gesture-handler";
import { FontAwesome5 } from "#expo/vector-icons";
import { MaterialCommunityIcons } from "#expo/vector-icons";
import { ActivityIndicator } from "react-native-paper";
function ProductsScreen() {
const navigation = useNavigation();
const [data, setData] = useState([]);
const [isLoading, setisLoading] = useState(true);
useEffect(() => {
const fetchData = async () => {
const data = await AsyncStorage.getItem("userData");
setData(data);
setisLoading(false);
};
fetchData();
}, []);
console.log(data);
return isLoading ? (
<ActivityIndicator />
) : (
<>
{data ? (
<FlatList
data={dataArray}
keyExtractor={(item) => item.name}
renderItem={({ item }) => (
<>
<Text>{item.brand}</Text>
<View style={styles.scan}>
<MaterialCommunityIcons
name="barcode-scan"
size={40}
color="black"
onPress={() => {
navigation.navigate("CameraScreen");
}}
/>
</View>
</>
)}
/>
) : null}
</>
);
}
export default ProductsScreen;
I would appreciate your comments please.
You could use ? (optional chaining) to confirm data doesnt yield to undefined before mapping.
data?.map((data, index) => {return <>....</>}
You need to return from data.map function to render the array items
return isLoading ? (
<ActivityIndicator />
) : (
<>
{data?.map((data, index) => {
return <View key ={index}>
<Text> {data.products_name_fr} </Text>
<Text> {data.brands} </Text>
<Text> {data.image_url} </Text>
<View style={styles.scan}>
<MaterialCommunityIcons
name="barcode-scan"
size={40}
color="black"
onPress={() => {
navigation.navigate("CameraScreen");
}}
/>
</View>
</View>;
})}
</>
);
Or short-hand of return
return isLoading ? (
<ActivityIndicator />
) : (
<>
data?.map((data, index) => (
<View key ={index}>
<Text> {data.products_name_fr} </Text>
<Text> {data.brands} </Text>
<Text> {data.image_url} </Text>
<View style={styles.scan}>
<MaterialCommunityIcons
name="barcode-scan"
size={40}
color="black"
onPress={() => {
navigation.navigate("CameraScreen");
}}
/>
</View>
</View>;
))
</>
);
I changed my code like this but I have the same error. Besides, the part of code which begins from: const styles=Stylesheet.create seems to be not active
import React, { useState, useEffect } from "react";
import { StyleSheet, Text, View, Button, AsyncStorage } from "react-native";
import { useNavigation } from "#react-navigation/core";
import { TouchableOpacity } from "react-native-gesture-handler";
import { FontAwesome5 } from "#expo/vector-icons";
import { MaterialCommunityIcons } from "#expo/vector-icons";
import { ActivityIndicator } from "react-native-paper";
import axios from "axios";
function ProductsScreen() {
const navigation = useNavigation();
const [data, setData] = useState([]);
const [isLoading, setisLoading] = useState(true);
useEffect(() => {
const fetchData = async () => {
const data = await AsyncStorage.getItem("userData");
setisLoading(false);
setData(data);
};
fetchData();
}, []);
return isLoading ? (
<ActivityIndicator />
) : (
<>
{data?.map((data, index) => {
return (
<>
key ={index}
<Text> {data.products_name_fr} </Text>
<Text> {data.brands} </Text>
<Text> {data.image_url} </Text>
<View style={styles.scan}>
<MaterialCommunityIcons
name="barcode-scan"
size={40}
color="black"
onPress={() => {
navigation.navigate("CameraScreen");
}}
/>
</View>
</>
);
})}
</>
);
const styles = StyleSheet.create({
products: {
alignItems: "center",
justifyContent: "center",
},
scan: {
marginLeft: 30,
position: "absolute",
bottom: 0,
right: 20,
marginBottom: 60,
marginRight: 30,
padding: 10,
borderRadius: 10,
backgroundColor: "#ff9234",
},
});
}
export default ProductsScreen;
I changed a little bit my code and I got another type of error : Invariant violation: Text strings must be rendered within a component. I will really appreciate your comments and support to fix this
return isLoading ? (
<ActivityIndicator />
) : (
<>
data?.map((data, index) => (
<>
<Text> {data.products_name_fr} </Text>
<Text> {data.brands} </Text>
<Text> {data.image_url} </Text>
<View style={styles.scan}>
<MaterialCommunityIcons
name="barcode-scan"
size={40}
color="black"
onPress={() => {
navigation.navigate("CameraScreen");
}}
/>
</View>
</>
))
</>
);
}
In the useEffect, set the data as array. Example
const = [data, setData] = useState([]); // do this in your state
setData([data]); //do this in your useEffet hook

How to pass props to FlatList with renderScene in react-native-tab-view?

I'm a newbie in React Native and trying to pass props to ListHeaderComponent in FlatList
Here's the code:
const FirstRoute = (props) => {
const _renderHeader = () => {
return(
<View>
{props.isFollowed &&
<TouchableOpacity onPress={props.onSubmit}>
<Text>You have followed this person</Text>
</TouchableOpacity> }
</View>
)
}
return(
<View style={[styles.scene, { backgroundColor: '#ff4081' }]}>
<FlatList
data={data}
keyExtractor={item => item.id}
renderItem={itemData => ( <Image source={itemData.item.id} style={{height: WIDTH/3, width: WIDTH/3}} />)}
ListHeaderComponent={_renderHeader}
/>
</View>
)
};
const SecondRoute = () => (
<View style={[styles.scene, { backgroundColor: '#673ab7' }]} />
);
const initialLayout = { width: Dimensions.get('window').width };
export default function Parent() {
const [index, setIndex] = React.useState(0);
const [routes] = useState([
{ key: 'first', title: 'First' },
{ key: 'second', title: 'Second' },
]);
const [_isFollowed, setIsFollowed] = useState(false);
const _onSubmit = () => {
...
setIsfollowed(true)
}
const renderScene = ({route}) => {
switch(route.key){
case 'first': return <FirstRoute {...props} onSubmit={_onSubmit} isFollowed={_isFollowed} />
case 'second': return <SecondRoute {...props} />
}
};
return (
<TabView
navigationState={{ index, routes }}
renderScene={renderScene}
onIndexChange={setIndex}
initialLayout={initialLayout}
/>
);
}
But when I save it, the screen logs the error: Can't find the value of isFollowed
I think the problem is at the way I pass the props. I'm still learning it. Since when I delete the ListHeaderComponent, the FlatList still generates the list of images well. And I don't know if it has something to do with renderScene
I really don't understand why
Please help me. Thank you very much
Let me get this straight. You need to render _renderHeader dinamically based on _isFollowed state. So, you passed to the first route as props your _onSubmit function and _isFollowed state in order to get to access them at _renderHeader. Right?
As I see you actually doesn't need to do it once your _renderHeader has direct access to both _isFollowed state and _onSubmit function. Try it out as bellow:
export default function Parent() {
const [index, setIndex] = React.useState(0);
const [routes] = useState([
{ key: 'first', title: 'First' },
{ key: 'second', title: 'Second' },
]);
const [_isFollowed, setIsFollowed] = useState(false);
const initialLayout = { width: Dimensions.get('window').width };
function _onSubmit() {
setIsFollowed(true);
}
function _renderHeader() {
return (
<View>
{_isFollowed &&
<TouchableOpacity onPress={_onSubmit}>
<Text>You have followed this person</Text>
</TouchableOpacity> }
</View>
);
}
const FirstRoute = () => {
return(
<View style={[styles.scene, { backgroundColor: '#ff4081' }]}>
<FlatList
data={data}
keyExtractor={item => item.id}
renderItem={itemData => ( <Image source={itemData.item.id} style={{height: WIDTH/3, width: WIDTH/3}} />)}
ListHeaderComponent={_renderHeader}
/>
</View>
)
};
const SecondRoute = () => (
<View style={[styles.scene, { backgroundColor: '#673ab7' }]} />
);
const renderScene = ({route}) => {
switch(route.key){
case 'first': return <FirstRoute />
case 'second': return <SecondRoute />
}
};
return (
<TabView
navigationState={{ index, routes }}
renderScene={renderScene}
onIndexChange={setIndex}
initialLayout={initialLayout}
/>
);
}
Other point I don't understand in your code and couldn't check cause I didn't try to run it was the function bellow:
function _renderHeader() {
return (
<View>
{_isFollowed &&
<TouchableOpacity onPress={_onSubmit}>
<Text>You have followed this person</Text>
</TouchableOpacity> }
</View>
);
}
If you want to render TouchableOpacity just in case _isFollowed is true you should do it using ternary operator like so:
function _renderHeader() {
return (
<View>
{_isFollowed ?
<TouchableOpacity onPress={_onSubmit}>
<Text>You have followed this person</Text>
</TouchableOpacity> }
: <></>
}
</View>
);
}

Screen switching by press on button react native

I just started to learn React-native. In this app I have a two buttons in header, first 'Todo', second 'Tags'. I want to chang content by press on these buttons. I think I need to change state.for clarityWhat I mean, when i tap on the button Tags, below I get TagScreen component, exactly the same for the button Todo. How to connect these components so that they work correctly?
app.js
import React, { useState } from 'react'
import { StyleSheet, View, FlatList } from 'react-native'
import { Navbar } from './src/Navbar'
import { TagScreen } from './src/screens/TagScreen'
import { TodoScreen } from './src/screens/TodoScreen'
export default function App() {
const [todos, setTodos] = useState([])
const [tags, setTags] = useState([])
const [appId, setAppId] = useState([])
const addTodo = title => {
setTodos(prev => [
...prev,
{
id: Date.now().toString(),
title
}
])
}
const addTags = title => {
setTags(prev => [
...prev,
{
id: Date.now().toString(),
title
}
])
}
const removeTags = id => {
setTags(prev => prev.filter(tag => tag.id !== id))
}
const removeTodo = id => {
setTodos(prev => prev.filter(todo => todo.id !== id))
}
return (
<View>
<Navbar title='Todo App!' />
<View style={styles.container}>
<TagScreen addTags={addTags} tags={tags} removeTags={removeTags}/>
{/* <TodoScreen todos={todos} addTodo={addTodo} removeTodo={removeTodo} /> */}
{/* HERE MUST CHANGED COMPONENTS */}
</View>
</View>
)
}
const styles = StyleSheet.create({
container: {
paddingHorizontal: 30,
paddingVertical: 20
}
})
navbar.js
import React from 'react'
import { View, Text, StyleSheet, Button, TouchableOpacity } from 'react-native'
export const Navbar = ({ title }) => {
return (
<View style={styles.padding}>
<View style={styles.navbar}>
<TouchableOpacity
style={styles.button}
>
<Text>Todo</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.button}
>
<Text>Tags</Text>
</TouchableOpacity>
<Text style={styles.text}>{title}</Text>
</View>
</View>
)
}
well you need to track the visiblity of what is visible in your state,
in your App component, do this;
const [showTodos, setShowTodos] = useState(false);
const makeTodosInvisible= () => setShowTodos(false);
const makeTodosVisible = () => setShowTodos(true);
return (
<View>
<Navbar onTodoPress={makeTodosVisible } onTagPress={makeTodosInvisible} title='Todo App!' />
<View style={styles.container}>
{showTodos
? <TodoScreen todos={todos} addTodo={addTodo} removeTodo={removeTodo} />
: <TagScreen addTags={addTags} tags={tags} removeTags={removeTags}/>
}
{/* <TodoScreen todos={todos} addTodo={addTodo} removeTodo={removeTodo} /> */}
{/* HERE MUST CHANGED COMPONENTS */}
</View>
</View>
)
and in your navbar.js do this
export const Navbar = ({ title, onTodoPress, onTagPress}) => {
return (
<View style={styles.padding}>
<View style={styles.navbar}>
<TouchableOpacity
style={styles.button}
onPreesed={onTodoPress} // will hide Tags and show Todos
>
<Text>Todo</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.button}
onPreesed={onTagPress} // will show Tags and hide Todos
>
<Text>Tags</Text>
</TouchableOpacity>
<Text style={styles.text}>{title}</Text>
</View>
</View>
)
}

Categories

Resources