I have a route like:
<Route component={Bar} path="/foo/:num"/>
I want to check if num exists in my database before rendering views inside Bar component. What I'm trying to do is utilizing component mounting functions as shown below to redirect to another route in case of invalid num:
import React, { Component } from 'react';
import {browserHistory} from 'react-router';
import { isNumExist } from '../../services/index.js';
class Bar extends Component {
componentWillMount(){
if (!isNumExist(this.props.params.num)){
browserHistory.push('/home');
}
}
render() {
...
}
}
Here goes index.js, defining isNumExist():
let foo = [...]; // Contains an array fetched from database
function isNumExist(num){
foo.map((element, i) => {
if (foo[i].num == num) {
return true;
}
});
return false;
}
Now on every page reload, the isNumExist() function triggers twice with false as output for second. So either num exists or not, the page redirects to the given route. Please correct me if I'm doing this in the wrong way or suggest the real issue preferably with details.
bar, useBarlet foo = [...]to make sure everything is running fine. Still having same issue