0

I am trying to migrate to recompose, but I am a little confused: I usually write some code in beginning of render() method, for example checking values, settings styles,... If I use recompose where can I write these codes? For example this :

render() {
        const { classes } = this.props;

        var startPos;
        if (this.props.isGeolocationAvailable && this.props.isGeolocationEnabled && this.props.coords != undefined) {
            console.log("location : " + this.props.coords.longitude + ":" + this.props.coords.latitude)
            this.state.initial_location = this.props.coords;
        }
        else {
            this.state.initial_location = { longitude: 0, latitude: 0 };
        }
...
AVEbrahimi
  • 17,993
  • 23
  • 107
  • 210
  • 1
    That is NOT how you should be setting state. You shouldn't even be setting state in `render`, it makes zero sense. – Andrew Li Sep 20 '17 at 04:40

1 Answers1

2

You should not set or modify any react's state in render() function. I suggest you to do this stuffs in constructor(props) like

constructor(props){
  super(props);
  let isGeoAvailable = this.props.isGeolocationAvailable && this.props.isGeolocationEnabled && this.props.coords != undefined;
  this.state = {
    initial_location: isGeoAvailable ? this.props.coords : { longitude: 0, latitude: 0 }
  }
}

For using recompose, You may want to separate like this

import { compose } from 'recompose';

const withGeoAvailable = (Component) = (props) => (
  props.isAvailable ? <Component {...props} /> : <p>GeoLocation is not available</p>
);

let enhancer = compose(withGeoAvailable)

let EnhancedMapComponent = enhancer(YourMapComponent)

render() {
  return <EnhancedMapComponent isAvailable={this.state.isAvailable} />
}

Btw, I suggest you to read this article, he simply explained about higher order component. https://www.robinwieruch.de/gentle-introduction-higher-order-components/