I am fetching an URL from a collection in Firebase linked to an alias field. This part of code is OK, but I can't manage to make a Redirect with the URL field of retrieved data. Here is my code:
import React from 'react'
import { useParams, Redirect } from 'react-router-dom'
import { FirebaseContext } from '../firebase'
function RedirUrl () {
const { alias } = useParams()
let link = ''
const { firebase } = React.useContext(FirebaseContext)
const dbRef = firebase.db.collection('links')
function getRedir () {
dbRef.where('alias', '==', alias).get().then(snapshot => {
link = snapshot.docs.map(doc => {
return { ...doc.data() }
})
console.log(link[0].longUrl) // it is okay
return link[0].longUrl
})
}
return <Redirect to={getRedir()} />
}
export default RedirUrl
And here the warning message:
Warning: Failed prop type: The prop
to
is marked as required inRedirect
, but its value isundefined
I guess the page is rendering before the retrieved data. Any help is appreciated.
<Redirect to={getRedir()} />
Here you are passing a promise to the to
prop, but it should receive a string. You can use useEffect
for getting the data from firebase:
const { alias } = useParams();
const { link, setLink } = useState('');
const { firebase } = React.useContext(FirebaseContext);
const dbRef = firebase.db.collection('links');
useEffect(() => {
dbRef
.where('alias', '==', alias)
.get()
.then((snapshot) => {
const links = snapshot.docs.map((doc) => {
return { ...doc.data() };
});
console.log(links[0].longUrl); // it is okay
setLink(links[0].longUrl);
});
}, []);
return link ? <Redirect to={link} /> : <></>;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.