Sunday, 9 April 2017

React - variable is undefined instead of true/false - component gets rendered first?

Alright, so what I'm trying to achieve is a function, that returns a Button with a different label depending on wether a file exists, or not. So far so good, the code itself seems to be working, but in the wrong order. What i did is print out 'file does exist' or 'does not exist' in the part of the function that does the actual checking, saving a boolean to a test variable, using said variable to determine which button gets returned in the end.

Now what happens it that, even if the first part prints out 'file does exist' (which should save true to test), console.log(test)a bit further down returns undefined which, of course, results in the conditional not to work.

I am sure I'm overlooking something very simple but I just can't figure it out.

import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import fs from 'fs';

var ConfigChecker = React.createClass({

  render: function(){

    var test;
    fs.open('./App.js', 'r', (err, fd) => {
      if (err) {
        if (err.code === 'ENOENT') {
          console.log('file does not exist');
          test = false;
        }

        throw err;
      }
      console.log('this should be executed first:');
      console.log('file does exist')
      test = true;
    });


    if (test)
    {
      console.log("this should be executed last:");
      console.log(test);
      return (<RaisedButton label="true" />);
    }
    else {
      console.log("this should be executed last:");
      console.log(test);
      return (<RaisedButton label="false" />);
    }
  }


});

export default ConfigChecker;



via TheHexaCube

No comments:

Post a Comment