Uploading image from react native to firebase storage - firebase

I have been looking for reference but I really can't find the issue why I can't find the reason why I am not able to upload image to the firebase storage. I am pretty sure that it is working as I am able to work authentication.
I even follow tutorials but for them, it is working. There is no error appearing but it doesn't upload for some reason and I am really frustrated already. Anyone know how to fix this?
import { StyleSheet, Text, View, Button, Image } from 'react-native';
import ImagePicker from 'react-native-image-crop-picker';
import React, { useState } from 'react';
import storage from '#react-native-firebase/storage';
const Home = () => {
const [img, setImg] = useState();
function choosePic(){
ImagePicker.openPicker({
width: 300,
height: 400,
cropping: false
}).then(async (image) => {
try {
setImg(image);
const imageName = image.path.substring(image.path.lastIndexOf("/") + 1);
const bucketFile = `image/${imageName}`;
const pathToFile = image.path;
await storage().ref(imageName).putFile(pathToFile);
const url = await storage().ref(bucketFile).getDownloadURL();
console.log('image url', url);
} catch (error) {
console.log(error)
}
})
.catch((error) =>{
console.log(error)
})
}
return (
<View>
<Image source={{ uri: img?.path}} style={{ width: 100, height: 100}}/>
<Button title='Add photo' onPress={choosePic} />
</View>
)
}
export default Home
const styles = StyleSheet.create({})
EDIT:
I wasted a lot of time looking for a relevant issue and found out that it is just taking too long to upload even the file size is below 1 MB (not even close).
Please help, even for authentication to login. It is also slow. My internet is fast and still don't understand what's wrong.

Related

How to retrieve image stored in firebase storage to my NextJs website?

I'm a beginner in NextJs and I'm having trouble fetching an image already stored in firebase storage to my website.
I've tried several solutions and none of them are working.
At this moment the console returns me this error:
"Image is missing required "src" property".
I didn't find much concrete information about this on google. I'm sure it will be useful for a lot of people.
I hope someone can help me, I've been stuck here for over 24 hours..
Here is my code:
import { useState, useEffect } from "react";
import { firebaseConfig } from "#/firebase/firebase";
import { initializeApp } from "#/firebase/firebase";
import { getStorage, ref, getDownloadURL } from "firebase/storage"
import styles from "../../styles/collections.module.css"
initializeApp(firebaseConfig);
export default function Test() {
const [url, setUrl] = useState();
useEffect(() => {
const func = async () => {
const storage = getStorage();
const reference = ref(storage, 'collections/amsterdam/bedroom/image10.avif');
await getDownloadURL(reference).then((x) => {
setUrl(x);
})
}
func();
}, []);
return (
<div className={styles.test}>
<div className={styles.test_container}>
<h1>Fetching image from firebase to NextJs project.</h1>
<Image
source={{ uri:url }}
width={500}
height={500}
alt=""
/>
</div>
</div>
)
}````
As the error states, you need to define the "src" property
<Image
src={url}
width={500}
height={500}
alt=""
/>

How to use useState in root layout/page in app directory of nextjs 13

In Nextjs 13 - experimental app directory, if I wanted to use useState on the root layout/page I must add ‘use client’ to the code, which effectively prevents all nested components from being server components.. how can I work around this so that I can use useState and still have server components. Thanks to any responders.
I don't know if this answers to your question (it's better to add some example code to help users understand your problem)
If you create a Server Component, and in that component you add your Client Component, it works fine. For example
ClientComponent.tsx
"use client";
import {useState} from 'react';
export default function ClientComponent() {
const [count, setCount] = useState(0);
return (
<>
<h1>Client Component</h1>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</>
)
}
ServerComponent.tsx
async function getData(){
const res = await fetch('http://localhost:3000/api/hello');
return await res.json();
}
export default async function ServerComponent() {
const data = await getData()
return (
<>
<h1>Server Component</h1>
<p>{data.name}</p>
</>
)
}
Api hello.ts
export default async function handler(req, res) {
res.status(200).json({ name: 'John Doe' })
}
Your page
import ClientComponent from "./ClientComponent";
import ServerComponent from "./ServerComponent";
export default function Page() {
return(<>
<ClientComponent/>
<ServerComponent/>
</>
)
}
In this example ServerComponent is rendered on the server, but ClientComponent on the client so it maintain interactivity
Hope this will help

How to connect Sanity to React Native

I have been trying for ages to make Sanity work with React Native and It's not working out, read multiple documentations, followed many tutorials but no luck.... What am i doing wrong?
Made a simple recreation here:
https://snack.expo.dev/#spts/smelly-candies
Please let me know what I'm doing wrong, or what I have to do to make it work
There are a few things wrong here, first I'll assume you meant Sanity and not Strapi:
Data isn't loading from Sanity because you need to enable CORS for the expo playground: see more details here
Make sure you set an apiVersion in sanity.js
There were a few issues with your React code which I've updated below, and should work once the CORS issue is resolved.
import React, { useState, useEffect } from 'react';
import { Text, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants';
import sanityClient from './sanity.js'
export default function App() {
const [stuff, setStuff] = useState([]);
useEffect(() => {
async function fetchData() {
const query = '*[_type == "post"] { title, content, emojiType }';
const data = await sanityClient.fetch(query);
setStuff(data)
}
fetchData()
}, [])
return (
<View>
<Text >
Change code in the editor and watch it change on your phone! Save to get a shareable url.
</Text>
<Text>{JSON.stringify(stuff)}</Text>
</View>
);
}

Best way to capture screen time and press events using React Native Expo and Firebase Analytics

My group and I are currently working on a mobile app using expo-cli and firebase as the backend. One of the requirements is we need to get users' screen time and record how frequently users press certain buttons. According to expo firebase documentation, it only supports limited Firebase Analysis. We were wondering what would be the best way to use Firebase Analytics with Expo to capture screen time and button pressed frequencies.
Screen Tracking
Screen tracking in React Native is different than in a native app since some navigation libraries run inside one Activity/Viewcontroller.
Assuming you are using react-native-navigation, which does have full native navigation support you can handle screen tracking like this.
import analytics from '#react-native-firebase/analytics';
import { Navigation } from 'react-native-navigation';
Navigation.events().registerComponentDidAppearListener(async ({ componentName, componentType }) => {
if (componentType === 'Component') {
await analytics().logScreenView({
screen_name: componentName,
screen_class: componentName,
});
}
});
Look here for the documentation
If you are using react-navigation you can still work around the lack of native screen support by hooking into the events that are provided.
import analytics from '#react-native-firebase/analytics';
import { NavigationContainer } from '#react-navigation/native';
const App = () => {
const routeNameRef = React.useRef();
const navigationRef = React.useRef();
return (
<NavigationContainer
ref={navigationRef}
onReady={() => {
routeNameRef.current = navigationRef.current.getCurrentRoute().name;
}}
onStateChange={async () => {
const previousRouteName = routeNameRef.current;
const currentRouteName = navigationRef.current.getCurrentRoute().name;
if (previousRouteName !== currentRouteName) {
await analytics().logScreenView({
screen_name: currentRouteName,
screen_class: currentRouteName,
});
}
routeNameRef.current = currentRouteName;
}}
>
...
</NavigationContainer>
);
};
export default App;
Here you can find a full example starter app.
Button Press Events
For logging press events there's a lot of documentation on the RNFirebase website.
A simple example to track a custom event that could be an onPress or anything would look like this:
import react, { useEffect } from 'react';
import { View, Button } from 'react-native';
import analytics from '#react-native-firebase/analytics';
function App() {
return (
<View>
<Button
title="Add To Basket"
onPress={async () =>
await analytics().logEvent('onPressAddToBasket', {
id: 3745092,
item: 'Your product name',
description: ['round neck', 'long sleeved'],
size: 'L',
wheneverYouWantToTrack: true,
})
}
/>
</View>
);
}

Github API Calls with personal access token Usage with Fetch with node JS and React JS

Today, I was playing around with GitHub API and I ran into the 60 calls per hour roadblock as described here - https://developer.github.com/v3/rate_limit/
For command line testing the solution is to use PAT - https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token
I am new learner but the GitHub doc was a little confusing so I had run around a lot. Github recommends the following CURL usage
curl -u GitHubUserName:personalaccesstoken https://api.github.com/users/GitHubUserName
but, then, using it in a fetch request is a challenge for there are a number of depreciation in the pipeline on how to use things.
So, the question, how best to get this working in a simple fetch call in node JS and React JS?
Eventually, I ended up with the following code block that gets it working.
import React, { useState, useEffect } from "react";
function GitHubUser({ login }) {
const [data, setData] = useState();
const [error, setError] = useState();
const [loading, setLoading] = useState(false);
useEffect(() => {
if (!login) return;
setLoading(true);
fetch(`https://api.github.com/users/GitHubUserName`,{
method: "GET",
headers: {
Authorization: `token personalaccesstoken `
}
})
.then(data => data.json())
.then(setData)
.then(() => setLoading(false))
.catch(setError);
}, [login]);
if (loading) return <h1>loading...</h1>;
if (error)
return <pre>{JSON.stringify(error, null, 2)}</pre>;
if (!data) return null;
return (
<div className="githubUser">
<img
src={data.avatar_url}
alt={data.login}
style={{ width: 200 }}
/>
<div>
<h1>{data.login}</h1>
{data.name && <p>{data.name}</p>}
{data.location && <p>{data.location}</p>}
</div>
</div>
);
}
export default function App() {
return <GitHubUser login="GitHubUserName" />;
}
The main confusion was that in some parts of GitHub documentation it keeps saying we should use username, and basic and what not. Perhaps it was only confusion for me, but this solves it.

Resources