how do I make an array in state - reactnative - react-native

I'm taking the images I uploaded to cloud storage, but the problem is the variable is not an array, so it is only storing just one url. How do I make variables with state array?
My code:
const reference = storage().ref('images');
const [imageUrl, setImageUrl] = useState();
const refer = storage().ref('images');
useEffect(() => {
try {
listFilesAndDirectories(reference).then(() => {
console.log('Finished listing');
});
refer.list().then(result => {
result.items.forEach(element => {
element.getDownloadURL().then(downloadUrl => {
setImageUrl(downloadUrl)
console.log(imageUrl)
console.log("=================")
}).catch(error =>{
alert(error)
})
})
})
} catch (error) {
alert(error);
}
}, []);

Is that what you are looking for?
const [items, setItems] = useState([]);
const handleStateChange = () => {
setItems(state => [...state, 'someNewItem']);
}
With useCallback
const handleStateChange = useCallback(function () {
setItems(state => [...state, 'someNewItem']);
}, [])

Related

How to pass the parameter to another screen using axios?

I'm doing the verification of the phone number, and I have to pass the phone number to the other checkCode.js component.
I have seen examples that pass it navigate() as a pramas, but how can I receive it in another component.
register.js
const SignUp = ({ navigation }) => {
const [phoneNumber, setPhoneNumber] = useState('');
let register = "https://app.herokuapp.com/api/v1/auth/register"
let sendVerification = "https://app.herokuapp.com/api/v1/auth/sendVerification-otp"
const signUp = () => {
const userParams = {
phone: phoneNumber,
};
const requestOne = axios.post(register, userParams)
const requestTwo = axios.post(sendVerification, userParams)
axios
.all([requestOne, requestTwo], userParams)
.then(axios.spread((...responses) => {
navigation.navigate('CodeVerification')
}))
.catch((err) => {
console.log('the error:', err.message);
})
}
checkCode.js
export default function CodeVerification({navigation}) {
//need phoneNumber param in this component
const [code, setCode] = useState('');
const confirm = () =>{
const userParams = {
phone: "+11111111",
code:code,
};
axios
.post('https://app.herokuapp.com/api/v1/auth/sendVerification-otp', userParams)
.then((response) =>{
console.log('response', response.data);
navigation.navigate('Welcome')
})
.catch((error) => {
console.log('the error:', error.message);
});
};
How can I pass it?
This might help
register.js
const SignUp = ({ navigation }) => {
// existing code remains the same
const signUp = () => {
....
axios
.all([requestOne, requestTwo], userParams)
.then(
axios.spread((...responses) => {
// send params like this
navigation.navigate("CodeVerification", {phone: phoneNumber});
})
)
.catch((err) => {
console.log("the error:", err.message);
});
};
};
checkCode.js
export default function CodeVerification({ route, navigation }) {
// get phoneNumber from props
const {phone} = route.params; // UPDATED this line
const [code, setCode] = useState("");
....
}
You can use Context Api
Context api is commonly used for transferring data to another component.

React Native: No thing show on the screen after getting data from firestore

This is my code:
const [tourists, setTourists] = useState(null)
const [saved,setsave]=useState('');
const {user, logout} = useContext(AuthContext);
const [userData, setUserData] = useState(null);
const [loading, setLoading] = useState(true);
const getUser = async() => {
await firestore()
.collection('users')
.doc( user.uid)
.get()
.then((documentSnapshot) => {
if( documentSnapshot.exists ) {
console.log('User Data in BookMark', documentSnapshot.data());
const list=[];
setUserData(documentSnapshot.data());
console.log('savedPosts: ',documentSnapshot.data().savedPosts);
documentSnapshot.data().savedPosts.map((object, index) => (
firestore().collection('posts').doc(object).get().then((querySnapshot) => {list.push(querySnapshot.data())})
))
setTourists(list);
if (loading) {
setLoading(false);
}
}
})
}
useEffect(() => {
getUser();
}, []);
return (
<View style={{flex: 1, marginTop: Constants.statusBarHeight}}>
{!loading ? ((tourists ||[]).map((object, index) => (...
I have checked through the console and see that firestore worked correctly, I got the data, tourists is not null, but the screen still shows nothing. Can anybody hekp me plz !!!
The issue is in this part:
const list=[];
setUserData(documentSnapshot.data());
console.log('savedPosts: ',documentSnapshot.data().savedPosts);
documentSnapshot.data().savedPosts.map((object, index) => (
firestore().collection('posts').doc(object).get().then((querySnapshot) => {list.push(querySnapshot.data())})
))
setTourists(list);
Becase you use then the setTourists(list) will always save an empty array because then finished after you already set the value. Also a map doesn't support async calls. We need to use a for loop for this.
Change your code to something like this:
const getUser = async () => {
await firestore()
.collection("users")
.doc(user.uid)
.get()
.then(async (documentSnapshot) => {
if (documentSnapshot.exists) {
console.log("User Data in BookMark", documentSnapshot.data());
const list = [];
const posts = [];
setUserData(documentSnapshot.data());
documentSnapshot.data().savedPosts.map((object, index) => {
posts.push(object);
});
for (let i = 0; i < posts.length; i++) {
const post = posts[i];
const docSnapshot = await firestore()
.collection("posts")
.doc(post)
.get();
list.push(docSnapshot.data());
}
setTourists(list);
if (loading) {
setLoading(false);
}
}
});
};

Getting variable from AsyncStorage and putting into Axios

I have been trying to get a variable from AsyncStorage and then put it into an Axios get request. The problem is that the variable is not updating to the data that is retrieved from AsyncStorage. How do I make it do that?
Here is my code:
const [sku, setSku] = useState('')
const STORAGE_KEY_SKU = '#save_sku'
const readSku = async () => {
try {
const selectedSku = await AsyncStorage.getItem(STORAGE_KEY_SKU)
if (selectedSku !== null) {
setSku(selectedSku)
}
} catch (e) {
alert('Failed to fetch the data from storage')
}
}
useEffect(() => {
readSku()
}, []);
useEffect(() => {
Axios.get(`https://api.vexdb.io/v1/get_matches?sku=${sku}`)
.then(({ data }) => {
//console.log("defaultApp -> data", data)
setData(data.result)
})
.catch((error) => console.error(error))
.finally(() => setLoading(false));
}, []);
Im trying to put get the sku variable from the state from AsyncStorage, but the ${sku} in the axios get request link is not working, the sku is blank in that statement.
Please help, thanks!
useFocusEffect(() => {
readSku()
}, []);
const STORAGE_KEY_SKU = '#save_sku'
// to get the session username from localstorage
const readSku = async () => {
try {
const selectedSku = await AsyncStorage.getItem(STORAGE_KEY_SKU)
if (selectedSku !== null) {
setSku(selectedSku)
}
} catch (e) {
console.log(e);
}
}
const setSku = async (selectedSku) => {
Axios.get(`https://api.vexdb.io/v1/get_matches?sku=${selectedSku}`)
.then(({ data }) => {
//console.log("defaultApp -> data", data)
setData(data.result)
})
.catch((error) => console.error(error))
.finally(() => setLoading(false));
}

How to assign value to global variable in fetch method in react native?

I am creating a react native app and I'm getting data from an API. I need to assign specific data into a global variable. That means my API return JSON data like {user_Id:"1' user_name:'abc' user_email:'abc#gmail.con'}. I need to assign user_Id into a global variable to access that in all of my screens.
This is what I tried;
componentDidMount() {
const arrFinal = [];
const {userDel} = this.state;
fetch('my API url')
.then(response => response.json())
.then(responseJson => {
// console.warn(responseJson);
arrFinal.push(responseJson);
arrFinal.map((item, index) => {
global.UserID = item.user_Id
})
.catch(error => {
console.error(error);
});
console.error(global.UserID)
}
But here nothing will print on console. How can I fix this problem?
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise
componentDidMount() {
const arrFinal = [];
const {userDel} = this.state;
fetch('my API url')
.then(response => response.json())
.then(responseJson => {
// console.warn(responseJson);
arrFinal.push(responseJson);
arrFinal.map((item, index) => {
global.UserID = item.user_Id
console.error(global.UserID)
})
.catch(error => {
console.error(error);
});
// console.error(global.UserID)
}
or :
async componentDidMount() {
const arrFinal = [];
const { userDel } = this.state;
const response = await fetch('my API url');
const responseJson = await response.json();
// console.warn(responseJson);
arrFinal.push(responseJson);
arrFinal.map((item, index) => {
global.UserID = item.user_Id;
console.error(global.UserID);
});
console.error(global.UserID);
}

Hash value null error in react-native hooks useEffect

the hash data I received using asyncStorage in my react native project is wrong. It actually works when I refresh the page. My request is probably running earlier than hash. However, I could not find a solution to this.
const [info, setInfo] = useState('');
const [hash, setHash] = useState(null);
const _retrieveData = async () => {
try {
const value = await AsyncStorage.getItem('hash');
setHash(value)
} catch (error) {
// Error retrieving data
}
};
useEffect(() => {
_retrieveData()
setTimeout(() => {
console.log(hash) //
axios.get(apiUrl + 'loginInfo?hash=' + hash)
.then(response => {
setInfo(response.data.message);
console.log('res', response);
});
}, 1000);
}, []);
The _retriveData method should be inside of the useEffect.
const [info, setInfo] = useState('');
const [hash, setHash] = useState(null);
useEffect(() => {
const _retrieveData = async () => {
try {
const hash = await AsyncStorage.getItem('hash');
return hash
} catch (error) {
console.log('error',error);
// Error retrieving data
}
};
const hash = _retrieveData()
setTimeout(() => {
console.log(hash) //
axios.get(apiUrl + 'loginInfo?hash=' + hash)
.then(response => {
setInfo(response.data.message);
console.log('res', response);
});
}, 1000);
}, []);
I solved the problem by getting help from a friend.
const [info, setInfo] = useState({});
const [hash, setHash] = useState(null);
const _retrieveData = useCallback(async () => {
try {
const value = await AsyncStorage.getItem('hash');
setHash(value);
} catch (error) {
// Error retrieving data
}
}, []);
const getInfo = useCallback(async () => {
try {
const response = await axios.get(apiUrl + 'loginInfo?hash=' + hash);
setInfo(response.data.message)
} catch (e) {
console.log(e);
}
}, [hash]);
useEffect(() => {
if (!hash) {
_retrieveData();
}
}, [hash])
useEffect(() => {
if (hash) {
setTimeout(() => {
getInfo();
},500)
}
}, [hash, getInfo]);