Q:

Function call after page reload in React

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.

A:

Your function will always return false because map function result is not returned. 
let foo = [...]; // Contains an array fetched from database
function isNumExist(num){
  foo.map((element, i) => {
    if (foo[i].num == num) {
      return true;
    }
  });
  return false;
}

foo.map(...) will return an array but it is not returned at any time. The function signature from the function that is inside the map function is only for that function itself.
so try :
let foo = [...]; // Contains an array fetched from database
function isNumExist(num){
   var good_numbers_length = 0;
   var length = foo.map((element, i) => {
    if (foo[i].num == num) {
      good_numbers_length += 1;
    }
  });
  if (good_numbers_length > 0)
  {
        return true;
  }  
  return false;
}

In addition, browserHistory.push('/home'); does not create a proper redirect. Change it to something like window.location = 'url' or something react friendly like react-router.

