Hello everyone i am new on React Native and i am trying to display some data i am fetching from firebase
Here is the data Json Shema i want to fetch
For now i just wrote a redux action creator like this
export const employeesFetch = () =>{
const {currentUser} = firebase.auth();
return(dispatch) => {
firebase.database().ref(`/users/${currentUser.uid}/employees`)
.on('value', snap => {
dispatch({type: EMPLOYEES_FETCH_SUCCESS, payload: snap.val()});
})
};
};
Here a screen Capture of my console :
Now how can i have access to each employee of each user and display each properties of them ?
Thanks you for your help ..
Related
I am trying to display user login info onto a React Material UI Typography label that is nested into an App bar(Header.js) by using data from another .js file(Login.js).
Here is the relevant code from the Header.js file:
<Typography color='textSecondary' className={classes.userText}>{}</Typography> // The label for the user info
and here is the data to be fetched from the Login.js file:
const [formData, updateFormData] = useState(initialFormData);
const handleChange = (e) => {
updateFormData({
...formData,
[e.target.name]: e.target.value.trim(),
});
};
const [error, setError] = useState();
const handleSubmit = (e) => {
e.preventDefault();
console.log(formData);
axiosInstance
.post(`token/`, {
email: formData.email, //the data I want to be displayed on the App Bar
password: formData.password,
})
.then((res) => {
localStorage.setItem('access_token', res.data.access);
localStorage.setItem('refresh_token', res.data.refresh);
axiosInstance.defaults.headers['Authorization'] =
'JWT ' + localStorage.getItem('access_token');
history.push('/');
//console.log(res);
//console.log(res.data);
}, reason =>{
console.error(reason);
setError("Invalid login details!")
alert("Login Failed!\nIncorrect login details!");
});
};
I am expecting to see the user email and display it in the Typography label...
you have to pass data from one component to another, and you really have 2 options here(excluding props drilling).
either you pass data using React's ContextAPI, which is easier assuming you are a newbie, or you can use Redux. There is not much to go from your code so you have to read docs here
contextApi: https://refine.dev/blog/usecontext-and-react-context/
redux: https://redux.js.org/tutorials/fundamentals/part-5-ui-react
I just started using redux.
In this project, I am using redux toolkit's createAsyncThunk to fetch data from firestore db inside a slice called orderSlice.
I am trying to loop through the data returned and display them on my orders component.
I am having issues figuring out what the issue is on this code
Here's my createAsyncThunk
//getting all orders from the database
export const getOrders = createAsyncThunk(
'orders/getOrders',
async(id = null, {rejectWithValue}) => {
const querySnapshot = await getDocs(collection(db, "transactions"));
querySnapshot.forEach((doc) => {
var data = doc.data();
data = ({...data, id: doc.id})
return data // console.log(data) returns my data
})
}'
)
When I console.log(data), I get my data back, which means the fetch request is working...
But the fetched orders are not passed to my component to be looped through.
Here's my extraReducer
[getOrders.fulfilled]: (state, action) => {
state.orders = action.payload
}
}
Here's my export
export const selectAllOrders = (state) => state.orders;
and my useSelector declaration
const orders = useSelector(selectAllOrders)
With getOrders imported from the orderSlice into the component, here's my useEffect
useEffect(() => {
dispatch(getOrders())
}, [dispatch])
This is where I am mapping through my fetched orders
{orders?.map(order => (
<article key={order.id}>
<p onClick={() => navigate(`/order/${order.id}`)}>{order.currency}{order.toRecieveAmount}{order.resellerName}</p>
within the next 24 hours</small>
<span>Transaction Status: {order.statusBuyer}</span>
</article>
)) }
What do you think I am doing wrong?
At what stage am I missing something?
I am relatively new to javascript and React and I am helping out with a project. I want to create a profile page for a signed in user with information stored in a firebase real time database. But the component is not rendering and the console shows 'Uncaught TypeError: Cannot read properties of null (reading 'username')'. I surmise it is because the data from the database is not being fetched before rendering. The data exists. The profile hook -
import React, { useEffect,useState } from 'react';
import {useAuth} from '../contexts/AuthContext'
import { getDatabase,ref, onValue} from "firebase/database";
function Profile(){
const [userData, setUserData] = useState({});
const currentUser = useAuth();
useEffect(()=>{ putData()
},[])
async function putData(){
let db = getDatabase();
let refd = ref(db,'users/'+ currentUser.currentUser.uid );
onValue(refd, (snapshot) => {
console.log(snapshot.val());
setUserData(snapshot.val());
},
(errorObject) => {
console.log('The read failed: ' + errorObject.name);
})
}
return(
<div>
<h3>Username : {userData.username}</h3>
<h3>Institute name : {userData.institute_name}</h3>
<h3>Accomodation : {userData.accomodation}</h3>
<h3>Phone no. : {userData.phone}</h3>
<h3>Email : {userData.email}</h3>
</div>
);
}
export default Profile;
Does the problem lie with the 'onValue' part or with the react part? Firebase documentation is not helping with my current understanding. Any help on how to accomplish this is appreciated.
useEffect(() => {
try {
//getting previously saved data
// console.log({ SelectedCaseDetails });
const getData = async () => {
const docRef = doc(
db,
"here comes your path to your document"
);
const docSnap = await getDoc(docRef);
console.log("data -->", docSnap.data());
if (docSnap.exists()) {
setData(docSnap.data());
setData(() => ({ ...docSnap.data() }));
}
};
getData();
} catch (error) {
console.log({ error });
}
}, []);
You just have to run your get data function in useEffect that runs when page is loading
Hope this helps 🤗
¯\(ツ)/¯
I'm quite new to Reactjs and Firebase so I'd need help.
I need to retrieve the data from the "0","1","2" keys (i.e. "Price", "Title", etc.) like I do with the "user" one.
In this parent component (Dashboard.js) I connect to the database:
import { useState, useEffect } from "react";
import OrderedItems from "./OrderedItems";
import classes from "./Dashboard.module.css";
import dash from '../../assets/dash.jpg';
import { auth } from "../../firebase";
import { useHistory } from "react-router-dom";
const Dashboard = () => {
const [ord, setOrd] = useState([]);
const history = useHistory();
useEffect(() => {
const fetchLps = async () => {
const query = `${auth.currentUser.uid}/Orders.json`
const response = await fetch(
"https://beatles-app-default-rtdb.europe-west1.firebasedatabase.app/" + query
);
const responseData = await response.json();
console.log(responseData);
const loadedOrd = [];
for (const key in responseData) {
loadedOrd.push({
id: key,
orderedItems: responseData[key].orderedItems,
});
}
setOrd(loadedOrd);
// setIsLoading(false);
};
fetchLps().catch((err) => {
let errorMessage =
"Something went wrong on our server! Please try again later.";
alert(errorMessage);
history.replace("/");
});
}, [history]);
const OrdList = ord.map((things) => (
<OrderedItems
key={things.id}
id={things.id}
orderedItems={things.orderedItems}
/>
));
return (
<section className={classes.cont}>
<div className={classes.welcome}>
<h1 className={classes.h1}>Welcome to your Dashboard!</h1>
<h3 className={classes.h3}> You can now start to shop. Go to the Shop page, select your favorite albums and go to Cart
in order to submit your order.</h3><br/>
</div>
{OrdList}
<img src={dash} alt="" width="100%" />
</section>
);
};
export default Dashboard;
console.log(responseData) output:
I retrieve the data in this child component (OrderedItems.js) using this syntax {props.user.address} (for example in this case I get "street" which is correct):
const OrderedItems = (props) => {
return (
<section>
<div>
<p>{props.user.address}</p> // THIS WORKS
<p>{props.orderedItems.0.Price}</p> // THIS DOESN'T WORK BECAUSE OF THAT 0 WHICH IS THE NAME OF THE FIREBASE KEY
</div>
</section>
);
};
export default OrderedItems;
Now the problem is that I can't do it with the above mentioned keys as the following syntax is not allowed because of that 0 number {props.orderedItems.0.Price}.
What should I do? The database structure is created automatically as I'm entering orders of multiple items using the POST method. So I suppose that the solution would be either to use a proper syntax (which I don't know at the moment) in order to access the data or to populate the database in a different way (but I don't think it is possible as Firebase does it on its own).
Thank you in advance!
I have a codes below, my poblem is the dispatch is fetching the previous userId paramater.
The flow is I go first to the users-list, and then go to user-info (displays right), but when I go back to users-list then go back to user-info (it does not display the right userId, instead the previous one).
import { fetchUserInfo } from '../../redux/users/slice';
const UserInfo = () => {
const usersId = useParams().id;
useEffect(() => {
console.log('->->userId', userId); // it logs exact id
dispatch(fetchUserInfo(usersId)).then((res) => { // it fetch previous id
// some codes here
console.log('fetchUser', res.data);
});
}, []);
}
Updated: I just figured out that it fetch correctly, its just the Content component is not updating.
In my Content.js component, I use useSelector to display slice state.
import { useSelector } from 'react-redux';
const Content = () => {
const { userDetails } = useSelector((state) => state.users);
return (
<div className="bg-basic-400 m-px-10 p-px-16">
<p>{userDetails.title}</p>
//more codes here
</div>
)
}
You need to add any relevant variable as a dependency in useEffect. If you use an empty [] it only runs once. you need to save userId in state.
const [usersId, setUsersId] = useState(useParams().id);
useEffect(() => {
console.log('->->usersId', userId); // it logs exact id
dispatch(fetchUserInfo(usersId)).then((res) => { // it fetch previous id
// some codes here
});
}, [usersId, fetchUserInfo]);