Async Storage not working (React native expo), no error given in console, but everytime I reload nothing is stored - javascript

I'm trying to use Async Storage for a note app, I created a component called task.js as a template for todos, an navigation.js component for nav, and home.js for the main screen all display with <navigation /> inapp.js, I added a funcction to store object value using async storage, but is not working, everytime I hard reload the app everything will be gone but it is not giving me any errors, I don't know where to start
here is my Home.js
import React, {useState} from 'react';
import { Keyboard, KeyboardAvoidingView, Platform, StyleSheet, Text,
TextInput, TouchableOpacity, View, SafeAreaView, ScrollView, Image } from 'react-native';
import Task from '../components/Task';
import AsyncStorage from '#react-native-async-storage/async-storage';
export default function Home({ navigation }) {
const [task, setTask] = useState();
const [taskItems, setTaskItems] = useState([]);
React.useEffect ( () => {
save(taskItems);
}, [taskItems])
React.useEffect (() => {
getsave();
}, [])
const handleAddTask = () => {
Keyboard.dismiss();
setTaskItems([...taskItems, task])
setTask(null);
}
const completeTask = (index) => {
let itemsCopy = [...taskItems];
itemsCopy.splice (index, 1);
setTaskItems(itemsCopy)
}
const save = async taskItems =>{
try {
const savetask = JSON.stringify(taskItems)
await AsyncStorage.setItem('tasksave', savetask)
} catch (e) {
console.log(e);
}
};
const getsave = async () => {
try {
const taskItems = await AsyncStorage.getItem('tasksave');
if (taskItems != null){
setTaskItems(JSON.parse(taskItems));
}
} catch (error) {
console.log(e);
}
};
return (
<SafeAreaView style={styles.container}>
<View style={styles.tasksWrapper}>
<Text style={styles.sectionTitle}>Your stuff:</Text>
<TouchableOpacity onPress={() => navigation.navigate('About')}>
<Text style={styles.about}>About</Text>
</TouchableOpacity>
<ScrollView style={styles.items}>{
taskItems.map((item, index) => {
return (
<View key={index}>
<TouchableOpacity onPress={ () => navigation.navigate("Gas", {item})}>
<Task text={item} navigation={navigation} />
</TouchableOpacity>
<TouchableOpacity onPress={() => completeTask(index)} style={styles.deleteW}>
<Image style={styles.delete} source={require('../components/remove.png')}></Image>
</TouchableOpacity>
</View>
)
})
}
</ScrollView>
</View>
<KeyboardAvoidingView
behavior={Platform.OS === "ios" ? "padding" : "height"}
style={styles.textwrapper}>
<TextInput style={styles.input} placeholder={'message'} value={task} onChangeText={text => setTask(text)}></TextInput>
<TouchableOpacity onPress={() => handleAddTask()}>
<View style={styles.addWrap}>
<Text style={styles.add}>+</Text>
</View>
</TouchableOpacity>
</KeyboardAvoidingView>
</SafeAreaView>
);
}
Here's my Task.js:
import React from "react";
import { View, Text, StyleSheet, Image, TouchableOpacity } from "react-native";
const Task = (props, {navigation}) => {
return (
<View style={styles.item}>
<View style={styles.itemleft}>
<Image style={styles.lightball} source={require('./arabic.png')}></Image>
<Text style={styles.itemtext}>{props.text}</Text>
</View>
<Image style={styles.arrow} source={require('./rightarrow.png')}></Image>
</View>
)
}
const styles = StyleSheet.create({
export default Task;
I hope is a quick read, I took out all the style stuff but this is still kinda long sorry, if you think it has something to do with my app.js or nav.js I can give you those too, I usually slove these bugs on my own but I just have no idea where to begin cause I'm not getting any error messages, thank you

Related

Possible Unhandled Promise Rejection (id: 0):

I need some tips about this error. I think the code might need a bunch of 'try' and 'catch' functions? I am new to this and I don't know how to properly implement them.
Question: should the audio recorder record audio even with this warning happening?( this code is meant to integrate an audio recorder: Audio recorder npm package link )
Btw I am running the latest version of react native, I also only wrote code inside App.js (besides giving android permisions and completing the post-installation process) since in the latest version of react the linking of packages becomes Auto-Link which means the linking happens on installing a package (Source: https://reactnative.dev/blog/2022/06/21/version-069 )
App.js :
import React, {Component} from 'react';
import AudioRecorderPlayer from 'react-native-audio-recorder-player';
import {
StyleSheet,
View,
TouchableOpacity,
} from 'react-native';
const App = () => {
const audioRecorderPlayer = new AudioRecorderPlayer();
const onStartRecord = async () => {
const result = await this.audioRecorderPlayer.startRecorder();
this.audioRecorderPlayer.addRecordBackListener((e) => {
this.setState({
recordSecs: e.currentPosition,
recordTime: this.audioRecorderPlayer.mmssss(
Math.floor(e.currentPosition),
),
});
return;
});
console.log(result);
};
const onStopRecord = async () => {
const result = await this.audioRecorderPlayer.stopRecorder();
this.audioRecorderPlayer.removeRecordBackListener();
this.setState({
recordSecs: 0,
});
console.log(result);
};
const onStartPlay = async () => {
console.log('onStartPlay');
const msg = await this.audioRecorderPlayer.startPlayer();
console.log(msg);
this.audioRecorderPlayer.addPlayBackListener((e) => {
this.setState({
currentPositionSec: e.currentPosition,
currentDurationSec: e.duration,
playTime: this.audioRecorderPlayer.mmssss(Math.floor(e.currentPosition)),
duration: this.audioRecorderPlayer.mmssss(Math.floor(e.duration)),
});
return;
});
};
const onPausePlay = async () => {
await this.audioRecorderPlayer.pausePlayer();
};
const onStopPlay = async () => {
console.log('onStopPlay');
this.audioRecorderPlayer.stopPlayer();
this.audioRecorderPlayer.removePlayBackListener();
};
return (
<View>
<View style={{backgroundColor:'black',alignSelf:'center',marginTop:'3%'}}>
<TouchableOpacity onPress={onStartRecord}>
<Text style={styles.twhite}>Start Record</Text>
</TouchableOpacity>
</View>
<View style={{backgroundColor:'black',alignSelf:'center',marginTop:'3%'}}>
<TouchableOpacity onPress={onStopRecord}>
<Text style={styles.twhite}>Stop Record</Text>
</TouchableOpacity>
</View>
<View style={{backgroundColor:'black',alignSelf:'center',marginTop:'3%'}}>
<TouchableOpacity onPress={onStartPlay}>
<Text style={styles.twhite}>Start Play</Text>
</TouchableOpacity>
</View>
<View style={{backgroundColor:'black',alignSelf:'center',marginTop:'3%'}}>
<TouchableOpacity onPress={onPausePlay}>
<Text style={styles.twhite}>Pause Play</Text>
</TouchableOpacity>
</View>
<View style={{backgroundColor:'black',alignSelf:'center',marginTop:'3%'}}>
<TouchableOpacity onPress={onStopPlay}>
<Text style={styles.twhite}>Stop Play</Text>
</TouchableOpacity>
</View>
</View>
);
};
const styles = StyleSheet.create({
twhite: {
color:'white',
fontSize:18,
},
});
export default App;

Application Breaks when adding custom component as import

I am having an issue where I have created two components "TaskInputField.js" and "TaskItem.js" and when I import them into the file I want to use them in, the browser window I am viewing the app on turns completely blank (using expo). Can post screenshots of what I mean if needed.
This has never happened to me before where simply importing a file breaks the application.
If I remove the imports from GroceryList.js and remove where I use them in the file, everything else runs just fine. I followed a guide for most of this also so I am unsure what is happening.
Thanks in advance.
For reference:
TaskInputField.js
import React, {useState} from 'react';
import { KeyboardAvoidingView, StyleSheet, View, TextInput, TouchableOpacity, } from "react-native";
import { MaterialIcons } from '#expo/vector-icons';
export default TaskInputField = (props) => {
const [task, setTask] = useState();
const handleAddTask = (value) => {
props.addTask(value);
setTask(null);
}
return (
<KeyboardAvoidingView
behavior={Platform.OS === "ios" ? "padding" : "height"}
style={styles.container}
>
<TextInput style={styles.inputField} value={task} onChangeText={text => setTask(text)} placeholder={'Write a task'} placeholderTextColor={'#fff'}/>
<TouchableOpacity onPress={() => handleAddTask(task)}>
<View style={styles.button}>
<MaterialIcons name="keyboard-arrow-up" size={24} color="black" />
</View>
</TouchableOpacity>
</KeyboardAvoidingView>
);
}
TaskItem.js
import React from 'react';
import { StyleSheet, Text, View, TouchableOpacity, } from "react-native";
import { MaterialIcons } from '#expo/vector-icons';
export default TaskItem = (props) => {
return (
<View style={styles.container}>
<View style={styles.indexContainer}>
<Text style={styles.index}>{props.index}</Text>
</View>
<View style={styles.taskContainer}>
<Text style={styles.task}>{props.task}</Text>
<TouchableOpacity onPress={() => props.deleteTask()}>
<MaterialIcons style={styles.delete} name="delete" size={18} color='#fff' />
</TouchableOpacity>
</View>
</View>
);
}
I am implementing these here in GroceryList.js
import React, {useState} from 'react';
import { Keyboard, ScrollView, StyleSheet, Text, View } from 'react-native';
import TaskInputField from '../../components/TaskInputField';
import TaskItem from '../../components/TaskItem';
export default function GroceryList() {
const [tasks, setTasks] = useState([]);
const addTask = (task) => {
if (task == null) return;
setTasks([...tasks, task]);
Keyboard.dismiss();
}
const deleteTask = (deleteIndex) => {
setTasks(tasks.filter((value, index) => index != deleteIndex));
}
return(
<View style={styles.container}>
<Text style={styles.heading}>Grocery List</Text>
<ScrollView style={styles.scrollView}>
{
tasks.map((task, index) => {
return (
<View key={index} style={styles.taskContainer}>
<TaskItem index={index + 1} task={task} deleteTask={() => deleteTask(index)}/>
</View>
);
})
}
</ScrollView>
<TaskInputField addTask={addTask}/>
</View>
)
}

My audios from firebase realtime database are not playing using touchable opacity in react native after certain iterations/count

I have 29 pronunciations stored in firebase storage and then from there with the help of access token, they're stored in realtime database. In UI, I've touchable opacity (in react native) to play those pronunciations one after the other in order. All pronunciations are getting played really fine and correctly till the 20th pronunciation but as long as i come at the 21st pronunciation, nothing is getting played from there onwards i have no idea why (by the way I have next and back buttons to show my data in order from database). But my other data (Text and images) is displayed correctly and normally, there's only a problem with audios. Can someone help me how to solve this problem? Also I have the same problem whether I use ref().on or ref().once. Here's the code given below:
import React from "react";
import Sound from "react-native-sound";
import database from '#react-native-firebase/database';
import {View, StyleSheet, Text, Image, ToastAndroid, Modal, TouchableOpacity} from 'react-native';
import { useState } from "react";
import { useEffect } from "react";
export default alphl=({navigation})=> {
const [myData,setData] = useState({
letter:'',
word:'',
wmeaning:'',
wimage:'',
apronun:'',
wpronun:'',
});
const [show, setshow]=useState(false);
const [wait, setwait]=useState();
const [img,setimg] = useState(null);
const [apronunn,setapronun] = useState(null);
const [wpronunn,setwpronun] = useState(null);
const [hey,sethey] = useState(1);
function inchey(){
sethey(hey + 1);
}
function decchey(){
sethey(hey - 1);
}
useEffect(() => {
ToastAndroid.showWithGravity('Wait! Loading...', ToastAndroid.LONG, ToastAndroid.CENTER);
getDatabase();
}, [hey]);
function getDatabase() {
database().ref('alphabets/'+hey+'/').once('value' , (snapshot) => {
console.log(snapshot.val());
// Sound.setCategory('Playback', true);
setwait(true);
var poo=new Sound(snapshot.val().apronun);
var pooo=new Sound(snapshot.val().wpronun);
setData({
letter: snapshot.val().letter,
word: snapshot.val().word,
wmeaning: snapshot.val().wmeaning,
wimage: setimg(snapshot.val().wimage),
apronun: setapronun(poo),
wpronun: setwpronun(pooo)
});
setwait(false);
});
// database().ref().off();
}
return (
<Text style={styles.lettertext}>
{myData ? myData.letter : 'loading...' }
</Text>
<TouchableOpacity onPress={() => {
return apronunn.play();
}}
disabled={wait}
style={styles.button}
>
<Text style={styles.buttontext}>Letter Pronunciation</Text>
</TouchableOpacity>
<Text style={styles.toptext}>
Word: {myData ? myData.word : 'loading...' }
</Text>
<Text style={styles.toptext}>
Meaning: {myData ? myData.wmeaning : 'loading...' }
</Text>
<TouchableOpacity onPress={() => {
return wpronunn.play();
}}
disabled={wait}
style={styles.button}
>
<Text style={styles.buttontext}>Word Pronunciation</Text>
</TouchableOpacity>
<Image style={{width:200, height:200, borderRadius:10, marginBottom:15}}
source={{uri: img}}
/>
<View>
<TouchableOpacity onPress={ () => {
if (hey>28) {
ToastAndroid.showWithGravity('Error! This is the last alphabet', ToastAndroid.CENTER, ToastAndroid.CENTER);
}
else {
inchey();
}
}}
style={styles.buttonnb}
>
<Text style={styles.buttontext}>Next</Text>
</TouchableOpacity>
<TouchableOpacity onPress={ async () => {
if (hey<2) {
ToastAndroid.showWithGravity('Error! Can not go back further', ToastAndroid.CENTER, ToastAndroid.CENTER);
}
else {
decchey();
}
}}
style={styles.buttonnb}
>
<Text style={styles.buttontext}>Back</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => navigation.navigate('alpht')}
style={styles.button}
>
<Text style={styles.buttontext}>Give Test</Text>
</TouchableOpacity>
</View>
</View>
);
}

Undefined is not an object (...) react native

I have a problem with React-Native. I want to show data from Django to React-Native, but I can't show one data, this is the code:
import React, { useState, useEffect } from "react";
import { StyleSheet, View, Text, Image, FlatList } from "react-native";
import client from "./../../api/client";
const DetailView = ({navigation, route}) => {
const [detail, setDetail] = useState("");
const { objurl } = route.params;
const getDetail = async (url) => {
try {
const response = await client.get(url);
if (!response.ok) {
setDetail(response.data);
}
} catch (error) {
console.log(error);
}
};
useEffect(()=>{ getDetail(objurl); }, [])
console.log(detail.habilidad_usuario.nombre_habilidad);
return (
<View style={styles.center}>
<Image
style={styles.usuarioImage}
source={{
uri: detail.foto_usuario,
}}
/>
<Text style={styles.name}>{detail.nombre_usuario} {detail.apellido_usuario}</Text>
<Text style={styles.name}>{detail.habilidad_usuario.nombre_habilidad}</Text>
<Text style={styles.description}>{detail.descripcion_usuario} </Text>
<Text style={styles.body}>Dirección: {detail.direccion_usuario} </Text>
<Text style={styles.body}>Celular: {detail.id_usuario} </Text>
<FlatList
data={detail.usuario_comentado}
keyExtractor={(item) => item.id.toString()}
renderItem={({ item }) => {
return (
<Text style={styles.body}>Comentario: {item.contenido_comentario} </Text>
);
}}
/>
</View>
);
}
The problem is in the line:
<Text style={styles.name}>{detail.habilidad_usuario.nombre_habilidad}</Text>
and It's the result:
enter image description here
The others data is rendering very well.
The data from Django Rest is:
enter image description here

Conditional rendering with React Hooks : loading

I am learning how to use React Hooks and have been stuck for many hours on something that's supposed to be very simple.
I am trying to display a a text if the state variable "loading" is true. If it's false, I want to display something else.
No matter what I try, "loading" is always false or at least, the UI does not appear to reflect its value.
here is the code:
import React, {useState, useEffect} from 'react';
import {View, SafeAreaView, Text} from 'react-native';
const testScreen= (props) => {
const [loading, setLoading ] = useState(true);
useEffect(() => {
setLoading(false);
}, []);
if(loading)
{
return <Text>Hi</Text>;
}
else
{
return<Text.Hey</Text>
}
}
export default testScreen;
Any help will be more than welcome and I am sorry if this is very basic.
UPDATE: Here is the actual code I am working with. SetLoading is supposed to update the state variable to false but never does or at least, the UI des not render.
import React, {useState, useEffect} from 'react';
import {View, SafeAreaView, Text, ActivityIndicator} from 'react-native';
import CategoryTag from '../Components/CategoryTag';
import firestore from '#react-native-firebase/firestore';
const CategoryScreen = (props) => {
const topicCollection = firestore().collection('Topics')
.where("active","==",true);
//hooks for topics
const [topics,setTopics] = useState([]);
const [loading, setLoading ] = useState(true);
//get all active topics
useEffect(() => {
return topicCollection.onSnapshot(querySnapshot => {
const list = [];
querySnapshot.forEach(doc => {
const { active, name } = doc.data();
list.push({
id: doc.id,
active,
name,
});
});
setTopics(list);
setLoading(false);
});
}, []);
const renderTopics = () =>{
return(
topics.map((item) =>{
return(
<CategoryTag key = {item.id}
color={userTopics.includes(item.name) ?"#51c0cc":"#303239"}
name = {item.name}
isSelected = {userTopics.includes(item.name)}
handleClick = {addTopicToUserTopicCollection}
/>
)
})
)
}
if(loading)
{
return (
<SafeAreaView style={{flex:1, backgroundColor:"#455a65"}}>
<View style={{width:200, padding:20, paddingTop:60}}>
<Text style ={{fontSize:25, fontWeight:"bold",
color:"#fff"}}>What are you</Text>
<Text style ={{fontSize:22, color:"#fff"}}>interested in?
</Text>
</View>
<View style={{flex:1, alignItems:"center",
justifyContent:"center", alignSelf:"center"}}>
<ActivityIndicator />
</View>
</SafeAreaView>
)
}
else // this never runs
{
return (
<SafeAreaView style={{flex:1, backgroundColor:"#455a65"}}>
<View>
<View style={{width:200, padding:20, paddingTop:60}}>
<Text style ={{fontSize:25, fontWeight:"bold",
color:"#fff"}}>What are you</Text>
<Text style ={{fontSize:22, color:"#fff"}}>interested in?
</Text>
</View>
<View style ={{flexDirection:"column", paddingTop:20}}>
<View style ={{padding:15, paddingTop:15,
marginBottom:15,
flexWrap:"wrap", flexDirection:"row"}}>
{renderTopics(topics)}
</View>
</View>
</View>
</SafeAreaView>
);
}
}
export default CategoryScreen;
You are immediately setting your setLoading state to false and therefore loading text might be rendering for fraction of second, or not at all, like a glitch. Try setting setLoading with a timeout and then you will see the intended behaviour.
const TestScreen= (props) => {
const [loading, setLoading ] = useState(true);
useEffect(() => {
setTimeout(()=>setLoading(false), 3000);
}, []);
if(loading)
{
return <Text>Hi</Text>;
}
else
{
return<Text>hey</Text>
}
}

Categories