preact-router
preact-router copied to clipboard
URL to profile
So here is my small issue, with PHP I know how to do the following, but preact is a bit different then PHP duh!
Basically we are using mongodb as our database, I want when a user types in http://example.com/fr46717 or any combination it should then go to a function to search the DB and it will return a profile for that ID, if it is not in the db then it should either show 404 error page (if we don't have that ID at ALL in our DB). However if we have the ID in our DB but it is not linked to a profile it should show an activate this ID page.
It should not select any menu item, as they all would be invalid.
I am wondering if anyone can point me in the right direction, I am sure I can figure out the DB side of it, but if someone could show me how I would add a route that is a match but only if it matches a profile in the DB
I am sure that there is a number of ways to do this, but my thinking is you really don't want to be running the function if the user has clicked on home or another link which is not a profile ID.
Hi @redimongo - since routing is synchronous, you can't do a DB lookup to determine if something is a match. Instead, I would recommend rendering your 404 page once that network call comes back:
class MyRoute extends Component {
componentDidMount() {
fetch(`/api/items/${this.props.id}`)
.then( r => r.json() )
.then( item => this.setState({ item }) )
.catch( error => this.setState({ error }) );
}
render({ id }, { item, error }) {
if (error) return <NotFound id={id} /> // your 404 component
return <div>Item {id} etc etc</div>
}
}