I am trying to fetch some user data from Firebase using getDoc and some data from MongoDB using axios in React.js.
Code:
async function getSolvedProblems() {
const docRef = await doc(db, "users-progress", user.uid);
await getDoc(docRef).then((doc) => {
console.log(doc.data());
});
}
useEffect(() => {
//fetch user's solved problems from firebase
getSolvedProblems();
//fetch problems from db server
axios
.get(process.env.REACT_APP_BACKEND_URL)
.then((res) => {
//doing something here
})
.catch((err) => {
console.log(err);
});
}, []);
But I don't know why the firebase data is not getting logged in console, when I hit refresh. But when I make any change in code, and save it, then it gets logged. I am unable to understand how useEffect is working here.
This is use effect work on below:
useEffect(() => {
//Runs only on the first render
}, []);
Also, you need to handle the catch block in your getSolvedProblems() method, see is there any error there.
On my guess, there is no value on user.uid when you load on page render
Related
fetchedAuthor is a author object. isFollow is his follower count. when someone clicks on folow isFollow changes. when isFollow changes i want to rerun useEffect. when the author changes, the fetchedAuthor changes but i dont want this useEffect to reRun as this is strictly for follower handling not author handling but at the same time when the author changes i want this useEfffect to know that author has changed so the next time when isFollow changes the useEffect doesnt fetch with the previous fetchedAuthor but the latest value of fetchedAuthor.
useEffect(() => {
setCurrentAuthor(fetchedAuthor) ;
},[fetchedAuthor]) ;
useEffect(async () => {
try {
const response = await fetch(`URL/${currentAuthor}/${isFollow}`);
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}},[isFollow]) ;
would this help me to get the appropriate response ?
Use a ref to store the current fetchedAuthor. Update the ref whenever fetchedAuthor changes. Use the ref's value when calling the api:
const authorRef = useRef(fetchedAuthor);
useEffect(() => {
authorRef.current = fetchedAuthor;
}, [fetchedAuthor]);
useEffect(async() => {
try {
const response = await fetch(`URL/${authorRef.current}/${isFollow}`);
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}, [isFollow]);
I have a JSON file called teams.json that contains the basic structure ("name", "age", "country", "role", "team", and "image") in an object. I'm using React to use the function fetch() to retrieve the data from the local JSON file. When I call the useEffect (shown below) hook, the data is retrieved from the local JSON file and I'm able call a useState function to store the data in a state variable called data.
useEffect() function call
//file path
filePath = "/src/public/teams.json"
const getData = (file) => {
fetch(file)
.then(res => res.json())
.then(data => setData(data))
.catch(err => console.log("Error fetching data", err)
}
useEffect(() => {
getData(filePath)
}, [filePath])
If I try to edit or access data within the useEffect() hook, the data is able to be retrieved without any problems, as such.
.then(data => console.log(data[0]))
This returns a json object that contains the necessary information.
{
"name":"R",
"image":"https://example.com",
"team":"B",
"role":"WB",
"country":"American",
"age":18
}
However, in the main body of my react App, if I try to obtain data from the data state, it gives me an error saying Cannot read properties of undefined, shown below.
Body of React App
return (
<main>
{data[0].country}
</main>
)
But I get this error:
I've tried solutions to previous forums from:
Stack Overflow Discussion Axios
Stack Overflow Discussion Error Axios
I've moved my project to the structure:
-src
--public
*some files*
and put the JSON file in the public folder. It reads it now but still doesn't render. I've also tried using axios but to no avail.
If this is an easy fix, sorry about that! Thanks for your help!
Because the data isn't loaded yet.
Assuming your app is something like
function App() {
const [data, setData] = React.useState();
const getData = (file) => {
fetch(file)
.then((res) => res.json())
.then((data) => setData(data))
.catch((err) => console.log("Error fetching data", err));
};
useEffect(() => {
getData(filePath);
}, [filePath]);
return <main>{data[0].country}</main>;
}
you're starting off with an undefined data.
Add a guard against that:
if(!data) return <>Loading...</>;
return <main>{data[0].country}</main>;
I was developing an app which I like implements Firebase as Authenticating system.
My problem comes when I try to set up the Authentication with Google provider when I try to modify the colletion of firestore where the users are saved. My code is the following:
export const loginWithGoogle = () => {
const navigation = useNavigation();
useEffect(() => {
setTimeout(() => {
navigation.navigate('/RegisterScreen');
}, 10000);
}, []);
return () => {
return firebase
.auth()
.signInWithPopup(Providers.google)
.then(async result => {
//console.log(result.credential.accessToken);
const user = result.user;
console.log(user);
//This 2 lines below doesn't work to get the colletion.
db.('users').setItem('userid', user!.uid);
collection.(db,'users').setItem('photoURL', user!.photoURL);
//TODO if userid exists IN USERS db then use update IF NULL use set
await db.collection('users').doc(user!.uid).update({
// id: user.uid,
name: user!.displayName,
email: user!.email,
phone: user!.phoneNumber,
photoURL: user!.photoURL,
});
})
.then(() => {
navigation.navigate('ProtectedScreen');
})
.catch(err => {
console.log(err);
});
};
};
So I guess that my error comes from unknowledge of how to manage data saved on firestore.
If you can help take thanks in advance !
There are some thing we need to clear here:
You can just merge the data. There is no need to read/get it from Firestore to check if it is there and save it onyl if it's not. You will be charged for reads and writes. In the end it's cheaper to always just write without checking if something exists.
Also this code here:
db.('users').setItem('userid', user!.uid);
collection.(db,'users').setItem('photoURL', user!.photoURL);
especially with the db.( and collection.( doens't look good. Even if it is it's not for getting data but for saving it.
Could you pls clarify witch Firebase SDK you use: version 8 or 9. Also pls check a little bit the docs here.
I am trying to fetch the api data and put it inside the tables, now i am using mock data
so I was able to write successfully actions and reducers.
now I am able to call the api.
but in the network call I am not see response in the api and seeing blocked response content status.
I am using react hooks for react and redux.
this is where I am making the api call
useEffect(() => {
getPosts(channel);
}, []);
can you tell me how to fix it.
providing my code snippet and sandbox below.
https://codesandbox.io/s/material-demo-kpt5i
demo.js
const channel = useSelector(state => state.channel);
const dispatch = useDispatch();
const getPosts = channel => dispatch(fetchPosts(channel));
useEffect(() => {
getPosts(channel);
}, []);
actions.js
export function fetchPosts(channel) {
return function(dispatch) {
dispatch(requestPosts());
return fetch(`http://jsonplaceholder.typicode.com/users`)
.then(
response => response.json(),
error => console.log("An error occurred.", error)
)
.then(json => {
dispatch(receivedPosts(json));
});
};
}
according to your sample on codesandbox, it is due to you are loading from https site but your source is from http. change http://jsonplaceholder.typicode.com/users to https://jsonplaceholder.typicode.com/users will solve your issue.
So i working with firebase auth and database in order to set new user to data base, if set successful i want to set claims for that user.
So it means i have a promise within a promise:
function setUser(user){
// no need for the database code before this, but userRef is set properly
return userRef.set(user)
.then(succ => {
return firebase.firebase.auth().setCustomUserClaims(user.key, {admin: true})
.then(() => {
console.log("setting claims")
return true;
});
})
.catch(err => {
return err
})
}
calling function:
app.post("/register_user",jsonParser,async (req, res) => {
var user = req.body.user;
let result = await fireBase.setUser(user);
res.send(result);
})
What happens is that i get the set on the database but claims are not set nor i can i see the log. I know its a js question and not firebase one. I tried many different ways (with await) but non worked.
firebase.firebase does not seem correct. You need to be using the admin object which can be initialised using const admin = require('firebase-admin'); This is not part of the firebase db sdk, but the admin one. You can also use the userRef.uid as that gives you the id of the document of the user, if that is what you want, else use your user.key
return admin.auth().setCustomUserClaims(userRef.uid, {
admin: true
}).then(() => {
//on success
});