i am facing a problem regarding async storage in react native - javascript

i am facing a problem regarding async storage in react native .
when i setItem in async storage and then retrieve it if there are 3 tasks- which i have added,
only two of them is retrieved
i will share a photo of before and after
this is output before refreshing
this is the output after refreshing the app
This is my app.js code
import { StatusBar } from 'expo-status-bar';
import {
StyleSheet,
Text,
View,
KeyboardAvoidingView,
FlatList,
TextInput,
TouchableOpacity,
Keyboard,
} from 'react-native';
import React, { Component } from 'react';
import * as Font from 'expo-font';
import Task from './components/Task';
import AppLoading from 'expo-app-loading';
import AsyncStorage from '#react-native-async-storage/async-storage';
let customFonts = {
Poppins_SemiBold: require('./assets/Poppins-SemiBold.ttf'),
Poppins_Regular: require('./assets/Poppins-Regular.ttf'),
};
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
task: '',
taskItems: [],
fontsLoaded: false,
};
}
async _loadFontsAsync() {
await Font.loadAsync(customFonts);
this.setState({ fontsLoaded: true });
}
componentDidMount() {
this._loadFontsAsync();
this._retrieveData()
}
_retrieveData = async () => {
try {
const value = await AsyncStorage.getItem('data');
if (value.length !== 2) {
// We have data!!
this.setState({taskItems:[...JSON.parse(value)]})
console.log(value);
}
} catch (error) {
// Error retrieving data
console.log(error)
}
};
handleAddTask=()=>{
Keyboard.dismiss()
this.setState({taskItems:[...this.state.taskItems,this.state.task]})
this.setState({task:''})
AsyncStorage.setItem('data',JSON.stringify(this.state.taskItems))
}
deleteItem=(index)=>{
try {
let arr = [...this.state.taskItems];
arr.splice(index, 1);
this.setState({taskItems:arr})
AsyncStorage.setItem('data',JSON.stringify(arr))
} catch (err) {
console.log(err);
}
}
render() {
if (!this.state.fontsLoaded) {
return <AppLoading />;
}
return (
<View style={styles.container}>
{/* Todays Tasks */}
<View style={styles.taskWrapper}>
<Text style={styles.sectionTitle}>Today's Tasks</Text>
<View style={styles.items}>
{/* This is where the tasks will go! */}
<FlatList
data={this.state.taskItems}
keyExtractor={(item) => item}
renderItem={({ item, index }) => (
<Task text={item} handleDelete={() => this.deleteItem(index)} />
)}
/>
</View>
</View>
{/* Write a Task */}
<KeyboardAvoidingView style={styles.writeTaskWrapper}>
<TextInput
style={styles.input}
placeholder={'Write A Task!'}
onChangeText={(text) => {
this.setState({ task: text });
}}
value={this.state.task}
/>
<TouchableOpacity
onPress={() => {
this.handleAddTask();
}}>
<View style={styles.addWrapper}>
<Text style={styles.addText}>+</Text>
</View>
</TouchableOpacity>
</KeyboardAvoidingView>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#E8EAED',
},
taskWrapper: {
paddingTop: 80,
paddingHorizontal: 20,
},
sectionTitle: {
fontSize: 24,
backgroundColor: '#fff',
fontFamily: 'Poppins_SemiBold',
borderRadius: 10,
margin: 'auto',
width: 250,
height: 60,
textAlign: 'center',
shadowColor: '#000',
shadowOffset: { width: 0, height: 1 },
shadowOpacity: 0.2,
shadowRadius: 2,
elevation: 5,
paddingTop: 10,
},
items: {
marginTop: 30,
},
writeTaskWrapper: {
position: 'absolute',
bottom: 60,
width: '100%',
flexDirection: 'row',
justifyContent: 'space-around',
alignItems: 'center',
},
input: {
paddingVertical: 15,
paddingHorizontal: 15,
backgroundColor: '#fff',
borderRadius: 60,
width: 250,
fontFamily: 'Poppins_Regular',
shadowColor: '#000',
shadowOffset: { width: 0, height: 1 },
shadowOpacity: 0.5,
shadowRadius: 2,
elevation: 3,
},
addWrapper: {
width: 60,
height: 60,
backgroundColor: '#fff',
borderRadius: 60,
justifyContent: 'center',
alignItems: 'center',
shadowColor: '#000',
shadowOffset: { width: 0, height: 1 },
shadowOpacity: 0.5,
shadowRadius: 2,
elevation: 3,
},
addText: {},
});
and this is my task.js code which is a component:
import React from 'react';
import {
View,
Text,
StyleSheet,
Dimensions,
Animated,
TouchableOpacity,
} from 'react-native';
import AppLoading from 'expo-app-loading';
import {
Poppins_100Thin,
Poppins_100Thin_Italic,
Poppins_200ExtraLight,
Poppins_200ExtraLight_Italic,
Poppins_300Light,
Poppins_300Light_Italic,
Poppins_400Regular,
Poppins_400Regular_Italic,
Poppins_500Medium,
Poppins_500Medium_Italic,
Poppins_600SemiBold,
Poppins_600SemiBold_Italic,
Poppins_700Bold,
Poppins_700Bold_Italic,
Poppins_800ExtraBold,
Poppins_800ExtraBold_Italic,
Poppins_900Black,
Poppins_900Black_Italic,
} from '#expo-google-fonts/poppins';
import { useFonts } from 'expo-font';
import Swipeable from 'react-native-gesture-handler/Swipeable';
const SCREEN_WIDTH = Dimensions.get('window').width;
const Task = (props) => {
let [fontsLoaded, error] = useFonts({
Poppins_100Thin,
Poppins_100Thin_Italic,
Poppins_200ExtraLight,
Poppins_200ExtraLight_Italic,
Poppins_300Light,
Poppins_300Light_Italic,
Poppins_400Regular,
Poppins_400Regular_Italic,
Poppins_500Medium,
Poppins_500Medium_Italic,
Poppins_600SemiBold,
Poppins_600SemiBold_Italic,
Poppins_700Bold,
Poppins_700Bold_Italic,
Poppins_800ExtraBold,
Poppins_800ExtraBold_Italic,
Poppins_900Black,
Poppins_900Black_Italic,
});
if (!fontsLoaded) {
return <AppLoading />;
}
const leftSwipe = (progress, dragX) => {
const scale = dragX.interpolate({
inputRange: [0, 100],
outputRange: [0, 1],
extrapolate: 'clamp',
});
return (
<TouchableOpacity onPress={props.handleDelete} activeOpacity={0.6}>
<View style={styles.deleteBox}>
<Animated.Text
style={{
transform: [{ scale: scale }],
color: '#fff',
fontFamily: 'Poppins_400Regular',
fontSize: 18,
}}>
Delete
</Animated.Text>
</View>
</TouchableOpacity>
);
};
return (
<Swipeable renderLeftActions={leftSwipe}>
<View style={styles.item}>
<View style={styles.itemLeft}>
<View style={styles.square}></View>
<Text style={styles.itemText}>{props.text}</Text>
</View>
<View style={styles.circular}></View>
</View>
</Swipeable>
);
};
const styles = StyleSheet.create({
item: {
backgroundColor: 'white',
padding: 15,
borderRadius: 10,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
marginBottom: 20,
shadowColor: '#000',
shadowOffset: { width: 0, height: 1 },
shadowOpacity: 0.5,
shadowRadius: 2,
elevation: 3,
},
itemLeft: {
flexDirection: 'row',
alignItems: 'center',
flexWrap: 'wrap',
},
square: {
width: 24,
height: 24,
backgroundColor: '#55BCF6',
opacity: 0.5,
borderRadius: 5,
marginRight: 15,
},
itemText: {
maxWidth: '80%',
fontFamily: 'Poppins_400Regular',
},
circular: {
width: 12,
height: 12,
borderColor: '#55BCF6',
borderWidth: 2,
borderRadius: 5,
},
deleteBox: {
backgroundColor: 'red',
justifyContent: 'center',
alignItems: 'center',
width: 100,
height: 55,
borderRadius: 10,
shadowColor: '#000',
shadowOffset: { width: 0, height: 1 },
shadowOpacity: 0.5,
shadowRadius: 2,
elevation: 5,
},
});
export default Task;

Due to React internal state update implementation, update Async storage run before new state updated. It's recommended to run asynchronous code before updating the state.
To solve the issue, refactor your code as below:
handleAddTask= async ()=>{
Keyboard.dismiss()
const updatedTaskItems = [...this.state.taskItems,this.state.task]
await AsyncStorage.setItem('data',JSON.stringify(updatedTaskItem))
this.setState({taskItems:updatedTaskUtems,task:''})
}

Related

Setting height in animated search bar react native

I have built an animated search bar in react native just like search bar of facebook mobile application. The search bar opens up when the search button is clicked on the header. It currently takes same height as the custom header that it is being rendered on. But i want to increase the height of the header to half the screen size when the search bar is on focus and set the height to default when the search bar is not focused. I have tried using my own logic but the problem was when i increased the height the contents of headers were shown below the search bar. And i dont want that. Can anyone help me how to resolve this?
/* eslint-disable #typescript-eslint/no-unused-vars */
import React, {useContext, useRef} from 'react';
import {
StyleSheet,
Text,
View,
TouchableOpacity,
Image,
SafeAreaView,
Animated,
TextInput,
Easing,
} from 'react-native';
import Logo from '#assets/images/NCLogo.png';
import Colors from '#constants/colors/colors';
import Search from '#assets/icons/Search.svg';
import Back from '#assets/icons/back-arrow.svg';
import {AuthContext} from '#components/ContextStore/AuthContext/AuthContext';
import DateAndDayGenerator from '#utils/DayGen';
import {HEIGHT, WIDTH} from '#utils/Dimensions';
import Metrics from '#constants/metrics/Metrics';
import Fonts from '#constants/fonts/fonts';
import SearchList from '#components/ListNews/SearchList';
interface Props {
news?: any;
}
const Header: React.FC<Props> = () => {
const date = new Date();
const dateAndDay = DateAndDayGenerator(date);
const {color} = useContext(AuthContext);
const [focused, setFocused] = React.useState(false);
const [value, setValue] = React.useState('');
const inputRef = useRef<TextInput>(null);
// animation initial value
const inputTranslateX = useRef(new Animated.Value(WIDTH)).current;
const backButtonOpacity = useRef(new Animated.Value(0)).current;
const contentTranslateY = useRef(new Animated.Value(HEIGHT)).current;
const contentOpacity = useRef(new Animated.Value(0)).current;
const handleClear = () => {
setValue('');
};
const handleBlur = () => {
setFocused(false);
const inputTranslateXConfig = {
toValue: WIDTH,
duration: 200,
useNativeDriver: true,
easing: Easing.inOut(Easing.ease),
};
const backButtonOpacityConfig = {
toValue: 0,
duration: 50,
useNativeDriver: true,
easing: Easing.inOut(Easing.ease),
};
const contentTranslateYConfig = {
toValue: HEIGHT,
duration: 0,
useNativeDriver: true,
easing: Easing.inOut(Easing.ease),
};
const contentOpacityConfig = {
toValue: 0,
duration: 200,
useNativeDriver: true,
easing: Easing.inOut(Easing.ease),
};
Animated.parallel([
Animated.timing(inputTranslateX, inputTranslateXConfig),
Animated.timing(backButtonOpacity, backButtonOpacityConfig),
Animated.timing(contentTranslateY, contentTranslateYConfig),
Animated.timing(contentOpacity, contentOpacityConfig),
]).start();
inputRef.current?.blur();
};
const handleFocus = () => {
setFocused(true);
const inputTranslateXConfig = {
toValue: 0,
duration: 200,
useNativeDriver: true,
easing: Easing.inOut(Easing.ease),
};
const backButtonOpacityConfig = {
toValue: 1,
duration: 200,
useNativeDriver: true,
easing: Easing.inOut(Easing.ease),
};
const contentTranslateYConfig = {
toValue: 0,
duration: 0,
useNativeDriver: true,
easing: Easing.inOut(Easing.ease),
};
const contentOpacityConfig = {
toValue: 1,
duration: 200,
useNativeDriver: true,
easing: Easing.inOut(Easing.ease),
};
Animated.parallel([
Animated.timing(inputTranslateX, inputTranslateXConfig),
Animated.timing(backButtonOpacity, backButtonOpacityConfig),
Animated.timing(contentTranslateY, contentTranslateYConfig),
Animated.timing(contentOpacity, contentOpacityConfig),
]).start();
inputRef.current?.focus();
};
return (
<>
<SafeAreaView style={styles.header_safe}>
<View style={styles.header}>
<View style={styles.view}>
<View style={styles.Logo}>
<Image source={Logo} style={styles.image} />
</View>
{color ? (
<View style={styles.texts}>
<Text style={[styles.text, {color}]}>Nepali Congress</Text>
<Text style={styles.date}>{`${dateAndDay.day}, ${
dateAndDay.month
} ${dateAndDay.date},${' '}${dateAndDay.year}`}</Text>
</View>
) : (
<View style={styles.texts}>
<Text style={styles.text}>Nepali Congress</Text>
<Text style={styles.date}>{`${dateAndDay.day}, ${
dateAndDay.month
} ${dateAndDay.date},${' '}${dateAndDay.year}`}</Text>
</View>
)}
<TouchableOpacity onPress={handleFocus}>
<View style={styles.search}>
<Search width={25} height={25} fill="none" />
</View>
</TouchableOpacity>
<Animated.View
style={[
styles.input,
{transform: [{translateX: inputTranslateX}]},
]}>
<Animated.View style={{opacity: backButtonOpacity}}>
<TouchableOpacity
activeOpacity={1}
style={styles.back_icon}
onPress={handleBlur}>
<Back width={28} height={28} fill="#000" />
</TouchableOpacity>
</Animated.View>
<TextInput
ref={inputRef}
placeholder="Enter title, description or date of news"
placeholderTextColor="#000"
clearButtonMode="while-editing"
onFocus={handleFocus}
value={value}
onChangeText={text => {
setValue(text);
}}
style={styles.input_text}
/>
<TouchableOpacity
onPress={handleClear}
style={styles.clearButton}>
<Text style={styles.clear}>X</Text>
</TouchableOpacity>
</Animated.View>
</View>
</View>
</SafeAreaView>
<Animated.View
style={[
styles.content,
{
opacity: contentOpacity,
transform: [{translateY: contentTranslateY}],
},
]}>
<SafeAreaView style={styles.content_safe}>
<View style={styles.content_inner}>
<View style={styles.separator} />
<SearchList searchPhrase={value} />
</View>
</SafeAreaView>
</Animated.View>
</>
);
};
const styles = StyleSheet.create({
header_safe: {
zIndex: 1000,
},
header: {
height: HEIGHT * 0.087,
paddingHorizontal: 16,
backgroundColor: Colors.white,
},
view: {
flex: 1,
overflow: 'hidden',
alignItems: 'center',
flexDirection: 'row',
justifyContent: 'space-between',
position: 'relative',
},
Logo: {
margin: 10,
alignItems: 'center',
flexDirection: 'row',
width: WIDTH * 0.15,
height: HEIGHT * 0.055,
},
image: {
width: '100%',
height: '100%',
resizeMode: 'stretch',
},
texts: {
marginLeft: 4,
marginRight: WIDTH * 0.155,
},
text: {
fontSize: Metrics.h3,
color: Colors.black,
fontFamily: Fonts.type.montBold,
width: WIDTH * 0.5,
},
date: {
marginTop: 4,
fontSize: Metrics.body7,
color: Colors.black,
fontFamily: 'Mont-Regular',
},
search: {
width: 35,
height: 35,
right: 20,
borderRadius: 80,
backgroundColor: '#f5f5f5',
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
},
input: {
height: HEIGHT * 0.087,
flexDirection: 'row',
alignItems: 'center',
position: 'absolute',
top: 0,
left: 0,
backgroundColor: Colors.white,
width: WIDTH - 32,
},
back_icon: {
width: 40,
height: 40,
borderRadius: 40,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
marginRight: 5,
transform: [{rotate: '180deg'}],
},
input_text: {
flex: 1,
height: 37,
backgroundColor: '#e4e6e8',
borderRadius: 80,
paddingHorizontal: 16,
fontSize: 13,
color: Colors.black,
},
input_text1: {
flex: 1,
height: 37,
backgroundColor: '#e4e6e8',
borderRadius: 80,
paddingHorizontal: 16,
fontSize: 13,
},
content: {
position: 'absolute',
width: WIDTH,
height: HEIGHT,
left: 0,
bottom: 0,
zIndex: 999,
},
content_safe: {
flex: 1,
backgroundColor: Colors.white,
},
content_inner: {
flex: 1,
paddingTop: HEIGHT * 0.087,
},
separator: {
height: 1,
marginTop: 5,
backgroundColor: '#e6e4eb',
},
search_results: {
alignItems: 'center',
borderBottomWidth: 1,
borderBottomColor: '#e6e4eb',
marginLeft: 16,
},
clearButton: {
width: 30,
height: 30,
borderRadius: 80,
marginLeft: 10,
backgroundColor: Colors.red,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
},
clear: {
fontSize: 14,
color: Colors.black,
fontWeight: 'bold',
},
});
export default Header;

React Native: Fetched data wont render as an object in react

I have the below code to dynamically render a component with data from an API. However I keep getting this error:
Error: Objects are not valid as a React child (found: object with keys {_U, _V, _W, _X}). If you meant to render a collection of children, use an array instead.
In the code I tried to create an array with the data but still continue to get the error. There is just one object that I extract from the API data to render.
import React, { useState } from 'react';
import { Button, View, Text, Image, TextInput, StyleSheet, ScrollView, SafeAreaView, TouchableOpacity } from 'react-native';
import { Video } from 'expo-av';
import { AsyncStorage } from 'react-native';
import { Ionicons } from '#expo/vector-icons';
export default async function Profile({navigation}) {
const [company, setCompany] = useState([])
const getData = async () => {
try {
const value = await AsyncStorage.getItem('company')
console.log(value)
fetchData(value)
if(value !== null) {
}
} catch(e) {
}
}
const fetchData = (name) => {
fetch("https://stonernautz.com/companies.json")
.then(response => {
return response.json()
})
.then(data => {
for(var i in data){
if(data[i].name == name)
console.log(data[i])
setCompany("["+JSON.stringify(data[i])+"]")
console.log(company)
}
})
}
useEffect(() => {
getData()
});
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor:"black",color:"white"}}>
<View style={styles.catView}>
<Ionicons name="arrow-back" color={'white'} size={26} style={{marginLeft:0, marginTop:10}} onPress={() => navigation.goBack()}/>
<Text style={{color:"white"}}>Back</Text>
</View>
<View style={{height:"60%",position:'absolute', top:110}}>
<ScrollView>
{company.map(user => (
<View style={{marginBottom:100}} key={user.name}>
<Video
source={{ uri: `${user.video}` }}
rate={1.0}
volume={1.0}
isMuted={false}
resizeMode="contain"
useNativeControls
style={{ width: 400, height: 250, maxWidth:"100%" }}
/>
<Image
style ={styles.image}
source={{ uri : `${user.logo}`}}
/>
<Text style={styles.name}>{user.name}</Text>
<TouchableOpacity
style={styles.button}
>
<Text>Connect</Text>
</TouchableOpacity>
</View>
))}
</ScrollView>
</View>
</View>
);
}
const styles = StyleSheet.create({
input: {
height: 40,
margin: 12,
borderWidth: 5,
borderBottomColor: '#000000',
borderTopColor: '#000000',
borderRightColor: '#000000',
borderLeftColor: '#000000',
padding: 10,
borderColor: "#000000"
},
image: {
width: 50,
height: 50,
borderRadius: 100,
overflow: "hidden",
marginTop: 20,
marginLeft:20
},
button: {
alignItems: "center",
backgroundColor: "white",
padding: 10,
width:200,
position:'absolute',
top:300,
left:'25%',
height:40,
justifyContent: 'center'
},
container: {
flex: 1,
paddingTop:10,
},
scrollView: {
position:'absolute',
top:80,
left:0,
marginHorizontal: 20,
maxHeight:400,
width:"90%",
maxWidth:"100%",
},
text: {
fontSize: 100,
marginLeft:10,
},
catText: {
color: "white",
fontSize:24,
marginLeft:40,
lineHeight:50
},
catView: {
paddingRight: 20,
position:"absolute",
top:50,
left:20
},
name: {
color:'white',
fontSize:20,
position:'absolute',
top:260,
left:110,
justifyContent: 'center',
alignItems: 'center'
},
});
getData is async so you should try to await the Promise with something like this:
useEffect(() => {
(async () => {
await getData()
})();
}, []);
I figured it out after A While, Here is what I did:
import React, { useState, Component } from 'react';
import { Button, View, Text, Image, TextInput, StyleSheet, ScrollView, SafeAreaView, TouchableOpacity } from 'react-native';
import { Video } from 'expo-av';
import { AsyncStorage } from 'react-native';
import { Ionicons } from '#expo/vector-icons';
const styles = StyleSheet.create({
input: {
height: 40,
margin: 12,
borderWidth: 5,
borderBottomColor: '#000000',
borderTopColor: '#000000',
borderRightColor: '#000000',
borderLeftColor: '#000000',
padding: 10,
borderColor: "#000000"
},
image: {
width: 50,
height: 50,
borderRadius: 100,
overflow: "hidden",
marginTop: 20,
marginLeft:20
},
button: {
alignItems: "center",
backgroundColor: "white",
padding: 10,
width:200,
position:'absolute',
top:300,
left:'25%',
height:40,
justifyContent: 'center'
},
container: {
flex: 1,
paddingTop:10,
},
scrollView: {
position:'absolute',
top:80,
left:0,
marginHorizontal: 20,
maxHeight:400,
width:"90%",
maxWidth:"100%",
},
text: {
fontSize: 100,
marginLeft:10,
},
catText: {
color: "white",
fontSize:24,
marginLeft:40,
lineHeight:50
},
catView: {
paddingRight: 20,
position:"absolute",
top:50,
left:20
},
name: {
color:'white',
fontSize:20,
position:'absolute',
top:260,
left:110,
justifyContent: 'center',
alignItems: 'center'
},
});
class ProductList extends Component {
constructor(props) {
super(props)
this.state = {
company: []
}
}
fetchData = (company) => {
//console.log("hi"+ company)
fetch("https://stonernautz.com/companies.json")
.then(response => {
return response.json()
})
.then(data => {
for(var i in data){
if(data[i].name == company){
this.setState({ company: data[i] })
//console.log(this.state)
}
}
})
}
componentDidMount = async () => {
const value = await AsyncStorage.getItem('company')
//console.log(value)
await this.fetchData(value)
}
render() {
return (
<View style={{backgroundColor:"black", height:"100%", alignItems:"center", justifyContent:"center"}}>
<Text style={{color:"white", alignItems:"center", justifyContent:"center"}}>{this.state.company.name}</Text>
</View>
)
}
}
export default ProductList;

Android app crashes when I open build app

Android app crashes when I open build app. It's happens only when I build app react native async storage. On iOS & Android emulators it's working stability. Help me please!
At first I thought that the problem was that I did not use JSON, but it turned out that I did not. JOHN tried, but nothing came of it. Maybe I am not saving correctly in Async Storage?
import React, { useState, useEffect } from 'react'
import { View, TextInput, StyleSheet, TouchableOpacity, ScrollView } from 'react-native'
import Icon from 'react-native-vector-icons/Octicons'
import BackNavbar from '../components/BackNavbar'
import { colors } from '../theme/theme'
import AsyncStorage from '#react-native-community/async-storage'
import GoalCard from '../components/GoalCard'
export default GoalScreen = ({ navigation }) => {
const STORAGE_KEY = '#data'
function goBack() {
navigation.goBack()
}
const [ goal, setGoal ] = useState([])
const [ goalScore, setGoalScore ] = useState()
const [ goalName, setGoalName ] = useState('')
const addGoal = () => {
setGoal([
... goal,
{
id: Date.now(),
text: goalName,
score: goalScore,
}
])
setGoalName('')
setGoalScore('')
}
const saveData = async (dataSave) => {
try {
await AsyncStorage.setItem(STORAGE_KEY, dataSave)
} catch (e) {
alert('Failed to save the data to the storage')
}
}
const loadData = async () => {
try {
const json = await AsyncStorage.getItem(STORAGE_KEY) || JSON.stringify([])
const loadData = JSON.parse(json)
if (loadData != null) {
setGoal(loadData)
alert(loadData.map())
}
} catch (e) {
alert('Failed to load the data to the storage')
}
}
useEffect(() => {
loadData()
}, [])
useEffect(() => {
saveData(JSON.stringify(goal))
}, [goal])
return (
<View style={styles.container}>
<BackNavbar title='Goals' back={goBack} />
<ScrollView>
{ goal.map( item => <GoalCard key={item.id} {... item} /> ) }
</ScrollView>
<View style={styles.inputView}>
<TextInput
keyboardType = "number-pad"
style={styles.inputTextScore}
value={goalScore}
onChangeText={score => setGoalScore(score)}
/>
<TextInput
style={styles.inputText}
value={goalName}
onChangeText={name => setGoalName(name)}
/>
<TouchableOpacity
style={styles.inputButton}
onPress={addGoal}
>
<Icon name="plus" size={26} color={colors.LIGHT_COLOR} />
</TouchableOpacity>
</View>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'flex-start',
},
inputView: {
marginTop: 15,
flexDirection: 'row',
width: '80%',
marginBottom: 15,
},
inputText: {
width: '62%',
height: 50,
paddingHorizontal: '5%',
right: 5,
borderRadius: 15,
backgroundColor: '#f2f2f2',
borderColor: colors.BORDER_COLOR,
color: colors.SECOND_COLOR,
borderWidth: 1,
fontSize: 20,
elevation: 3,
fontSize: 16,
},
inputTextScore: {
width: '20%',
height: 50,
marginRight: 10,
paddingHorizontal: '5%',
right: 5,
borderRadius: 15,
backgroundColor: '#f2f2f2',
borderColor: colors.BORDER_COLOR,
borderWidth: 1,
fontSize: 20,
elevation: 3,
color: colors.SECOND_COLOR,
fontWeight: '500',
},
inputButton: {
alignItems: 'center',
justifyContent: 'center',
paddingHorizontal: 15,
paddingVertical: 10,
borderRadius: 50,
backgroundColor: colors.MAIN_COLOR,
left: 5,
}
})

Make Search using firebase in react native

I am new to react native and firebase. I want to make a search bar that can search all data from firebase according to Barcode value, but I'm facing some errors while doing it. I think that my code is wrong somewhere but don't know where. I have transferred the firebase credentials to dbConfig.js . Here is my firebase data firebase data and my code:
import React,{Component} from 'react';
import { View, Text,TextInput,StyleSheet,Image, Button} from 'react-native';
import firebase from './dbConfig';
export default class ListItem extends Component {
render() {
return (
<>
<View style={styles.BackGround}>
<View style={styles.SectionStyle}>
<Image
source={require('./mic.png')} //mic image here
style={styles.ImageStyle}
/>
<TextInput
style={{ flex: 1, justifyContent: 'center', textAlign: 'center', fontSize: 12}}
placeholder="Search for Product"
underlineColorAndroid="transparent"
//onChangeText={(text) => this.setState({data: text})}
onSubmitEditing = {(text)=> this.setState({data: text})}
value = {this.state.data}
// onSubmitEditing={()=>this._search}
//onSubmitEditing={()=>this.componentWillMount}
/>
<Image
source={require('./usr.png')} //icon image here
style={styles.ImageStyle2}
/>
</View>
<View>
<Text>{this.state.items}</Text>
</View>
</View>
</>
);
}
constructor(props){
super(props);
this.state= {
items: '',
data: '',
};
}
componentWillMount(){
var ref = firebase.database().ref('/');
ref.child(this.state.data).on("value", snapshot =>{
console.log(snapshot.val().info.Price);
//if(snapshot.val().Price == this.state.data){
//this.setState({items: Object.values(snapshot.val())});
//}
//else{
//alert('there is problem');
//}
});
}
}
const styles = StyleSheet.create({
BackGround: {
backgroundColor: '#22abb6',
height: '100%'
},
SectionStyle: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#fff',
// borderWidth: 0.8,
// borderColor: '#000',
shadowColor:'#176f75',
marginTop: 50,
height: 40,
borderRadius: 10,
margin: 10,
},
ImageStyle: {
padding: 10,
marginLeft: 10,
margin: 5,
height: 25,
width: 25,
resizeMode: 'stretch',
alignItems: 'center',
},
ImageStyle2: {
padding: 10,
marginLeft: 10,
marginRight: 10,
margin: 5,
height: 25,
width: 25,
resizeMode: 'stretch',
alignItems: 'center',
},
});
I did it by changing the follows:
//adding this in TextInput
onSubmitEditing = {this.componentWillMount}
//on changing the function compoundWillMount to async()
componentWillMount= async()=>{

Take picture, save and access Camera with react-native

I am studing react-native a 4 months and I am Build my App. I got problems with Camera. I am trying to take a picture, save and access the photo. I take a picture but I don't know where picture goes and how to acess.
I am using expo import camera, because when I use from react a get some error.
this is my code:
import React, {Component} from 'react';
import {Text, View, TouchableOpacity, Image,TouchableHighlight,Vibration} from 'react-native';
//import Camera from 'react-native-camera';
import {Camera, Permissions,} from 'expo';
const myStyle = {
container: {
flex: 1,
flexDirection: 'row',
},
preview: {
flex: 1,
justifyContent: 'flex-end',
alignItems: 'center'
},
capture: {
flex: 0,
backgroundColor: '#fff',
borderRadius: 5,
color: 'red',
padding: 10,
margin: 40
},
main2: {
flex: 1,
//alignItems: 'flex-start',
flexDirection: 'row',
justifyContent: 'space-between',
},
main: {
flex: 1,
},
borda: {
//flex: 0.1,
alignItems: 'flex-end',
backgroundColor: 'black',
height: 110,
},
borda2: {
backgroundColor: 'black',
width: 60,
},
borda3: {
width: 60,
backgroundColor: 'black',
},
borda4: {
height: 120,
backgroundColor: 'black',
//flex: 1,
alignItems: 'center',
flexDirection: 'row',
justifyContent:'space-between',
},
texto:{
fontSize: 18,
marginBottom: 40,
color: 'white',
},
textoButton:{
fontSize: 18,
color: 'white',
marginTop: 5,
},
button:{
alignSelf: 'flex-end',
alignItems: 'center',
backgroundColor:'transparent',
flexDirection: 'row',
justifyContent:'space-between'
},
cameraStyle:{
width: 70,
height: 57,
//margin:30,
alignItems: 'center',
tintColor: 'white',
},
flipStyle:{
width: 52,
height: 57,
marginLeft:10,
alignItems: 'center',
tintColor: 'white',
},
gallerystyle:{
width: 64,
height: 57,
marginLeft:10,
alignItems: 'center',
tintColor: 'white',
marginRight: 10,
},
closeStyle:{
width: 56,
height: 57,
marginTop: 30,
marginRight: 20,
alignItems: 'flex-end',
tintColor: 'white',
justifyContent:'flex-end'
},
box:{
width: 'auto',
justifyContent: 'space-between',
flexDirection: 'column',
alignItems: 'center',
},
};
export default class CameraAcess extends Component {
constructor(props) {
super(props);
this.state = {hasCameraPermission: null, type: Camera.Constants.Type.back,};
}
async componentWillMount() {
const {status} = await Permissions.askAsync(Permissions.CAMERA);
this.setState({hasCameraPermission: status === 'granted'});
}
snap = async function(){
if (this.camera) {
this.camera.takePictureAsync().then(data => {
FileSystem.moveAsync({
from: data,
to: '${FileSystem.documentDirectory}photos/Photo_${this.state .photoId}.jpg',
}).then(() => {
this.setState({
photoId: this.state.photoId + 1,
});
Vibration.vibrate();
})
.catch((e) => {
console.log(e, 'ERROR');
});
})
.catch((e) => {
console.log(e, 'takePicture ERROR');
});
}
console.log('I took the picture');
};
cameraPhoto = require('./Images/camera.png');
flipPhoto = require('./Images/flip.png');
closePhoto = require('./Images/close.png');
galleryPhoto = require('./Images/gallery.png');
render() {
const { main,main2, borda, borda2, borda3,borda4,cameraStyle,flipStyle,closeStyle,box,textoButton,gallerystyle} = myStyle;
const {hasCameraPermission} = this.state;
if (hasCameraPermission === null) {
return <View/>;
} else if (hasCameraPermission === false) {
return <Text>No access to camera</Text>;
} else {
return (
<View style={main}>
<Camera style={main} type={this.state.type}>
<TouchableHighlight onPress={() => {this.props.navigator.push({id: 'MenuPrincipal'});}}
style={borda} underlayColor={'black'} activeOpacity={0.6}>
<Image source={this.closePhoto} style={[closeStyle]}/>
</TouchableHighlight>
<View style={main2}>
<View style={[borda2]}/>
<View style={[borda3]}/>
</View>
<View style={[borda4]}>
<TouchableOpacity onPress={() => {this.setState({type: this.state.type === Camera.Constants.Type.back
? Camera.Constants.Type.front : Camera.Constants.Type.back,});}}>
<View style={box}>
<Image source={this.flipPhoto} style={[flipStyle]}/>
<Text style={textoButton}>
Flip
</Text>
</View>
</TouchableOpacity>
<TouchableOpacity onPress={() => {this.snap()}}>
<View style={box}>
<Image source={this.cameraPhoto} style={[cameraStyle]}/>
<Text style={textoButton}>
Capture
</Text>
</View>
</TouchableOpacity>
<TouchableOpacity onPress={() => {false}}>
<View style={box}>
<Image source={this.galleryPhoto} style={[gallerystyle]}/>
<Text style={textoButton}>
Gallery
</Text>
</View>
</TouchableOpacity>
</View>
</Camera>
</View>
);
}
}
}
Someone help me to solve this problem and please be especific and clearly in your explanation, every details are necessary to me. I need this to end my App.
If I were you I would do
console.log(data);
then you can see what the promise returns in the XDE. You should, at the very least, see the following properties: height, width, uri. Uri will show you exactly where that image is being stored in the cache.

Categories