react-instantsearch icon indicating copy to clipboard operation
react-instantsearch copied to clipboard

Error: You can't switch <InstantSearch> from being uncontrolled to controlled

Open ragunaru opened this issue 8 years ago • 2 comments

Hello,

I am trying to build a simple search app and ran into an issue where I get an error when I try to set searchState. I am basically trying to do a search for a range of values on 2 specific properties: latitude and longitude – a 'search around' for records on a map, if that makes sense.

I am running my React Native app on Expo and here is the error I'm getting: image

Here is my code:

import React from 'react';
import { View, Button, TouchableHighlight, Text, Dimensions } from 'react-native';
import { Location, Permissions, Constants } from 'expo';
import MapView, { AnimatedRegion, Animated, Marker } from 'react-native-maps';
import { InstantSearch, Configure } from 'react-instantsearch/native';
import { connectInfiniteHits, connectRange } from 'react-instantsearch/connectors';

// Import styles
import GeneralStyles from '../styles/GeneralStyles';
import FormElements from '../styles/FormElements';
import MapScreenStyles from '../styles/MapScreenStyles';

// Importing components
import CustomIcon from '../components/CustomIcon';



// Main map screen
export default class MapScreen extends React.Component {
  // Binding things, etc.
  constructor(props) {
    super(props);

    this.onRegionChange = this.onRegionChange.bind(this);
    this.onPressLocate = this.onPressLocate.bind(this);
    this.onSearchStateChange = this.onSearchStateChange.bind(this);
    this.setRangeParams = this.setRangeParams.bind(this);

    this.state = {
      location: null,
      errorMessage: null,
      region: null,
      userLocation: null,
      searchState: null,
    };
    console.log('----==== Search state in constroctur: ' + this.state.searchState);
  }

  getInitialState() {
    return {
      region: {
        latitude: 51.507624,
        longitude: -0.1264571,
        latitudeDelta: 0.04,
        longitudeDelta: 0.04,
      },
    };
  }

  onSearchStateChange() {
    console.log(this.state.searchState);
    console.log('+++++++++++++++++++++++ Is this happening?');
  };

  // Setting region to current map view
  onRegionChange(region, searchState) {
    this.setState({ region });
    console.log("Region has changed to: --------- " + JSON.stringify(region));
    // this.setRangeParams(region);
  }

  // Function to animate back to user's current location
  onPressLocate(region) {
    this._map.animateToRegion(region, 500);
    console.log('Region in my custom function is: --------- ' + JSON.stringify(region));
  }

  // Function to set geo range parameters
  setRangeParams(region) {
    // Calculating the min and max ranges for longitude & latitude for a range search
    minLongitude = region.longitude - region.longitudeDelta
    maxLongitude = region.longitude + region.longitudeDelta
    minLatitude = region.latitude - region.latitudeDelta
    maxLatitude = region.latitude + region.latitudeDelta
    console.log('---------------- Min & max longitude are: ' + minLongitude, maxLongitude);
    console.log('---------------- Min & max latitude are: ' + minLatitude, maxLatitude);
    console.log('====================== Search state is: ' + this.state.searchState);
    rangeSearch = {
      range: {
        lat: {
          min: minLatitude,
          max: maxLatitude
        },
        long: {
          min: minLongitude,
          max: maxLongitude
        }
      }
    }
    this.setState({ searchState: rangeSearch });
    console.log('====================== ?? Search state is: ' + JSON.stringify(this.state.searchState));
  }

  // Does what it says on the tin
  componentWillMount() {
    this._getLocationAsync();
  }

  // Mumbo jumbo function to get the user's current location
  _getLocationAsync = async () => {
    let { status } = await Permissions.askAsync(Permissions.LOCATION);
    if (status !== 'granted') {
      this.setState({
        errorMessage: 'You chose to not give access to your location.',
      });
    }

    let location = await Location.getCurrentPositionAsync({ enableHighAccuracy: true });

    region = {
      latitude: location.coords.latitude,
      longitude: location.coords.longitude,
      latitudeDelta: 0.04,
      longitudeDelta: 0.04,
    }
    // So I'm saving the user's current location to two variables,
    // one to set show it on the map, and second so we can locate back to the user
    this.setState({userLocation: region, region: region});

    // Making sure we set the params for a location based search
    this.setRangeParams(region);

    console.log('Original location is: --------- ' + JSON.stringify(this.state.region));
  };

  render() {
    const configuration = (
      <Configure />
    );
    return (
      <View style={ GeneralStyles.FullScreenContainer }>
        <InstantSearch
          appId="XYZ"
          apiKey="ABC"
          indexName="Venue"
          searchState={this.state.searchState}
          onSearchStateChange={this.onSearchStateChange}
        >
          {/* Just the map view */}
          <MapView
          ref={component => {this._map = component;}}
            style={ MapScreenStyles.MapContainer }
            region={this.state.region}
            onRegionChangeComplete={this.onRegionChange}
            showsUserLocation={true}
            showsCompass={true}
          >
            <Text></Text>
            <Marker
              coordinate={{latitude: 37.7858,
              longitude: -122.4064}}
              title={"This is marker"}
              description={"I describe"}
           />
          </MapView>
          <Text>Shit</Text>
          {/* /end map view */}
        </InstantSearch>
        {/* The bottom bar fake input thing */}
        <View style={[ MapScreenStyles.BottomBarContainer, GeneralStyles.AbsolutePosition ]}>
          <View style={MapScreenStyles.SearchButtonContainer}>
            <TouchableHighlight
              onPress={() => this.props.navigation.navigate('Search')}
              style={MapScreenStyles.SearchButton}
              underlayColor={'#F0F0F1'}
            >
              <View style={MapScreenStyles.SearchButtonFakeInput}>
                <CustomIcon name='zoom-2' size={16} color='#8E8E93' />
                <Text style={MapScreenStyles.SearchButtonText}>Where to next, Captain?</Text>
              </View>
            </TouchableHighlight>
            <TouchableHighlight
              onPress={() => {this.onPressLocate(this.state.userLocation)}}
              underlayColor={'#F0F0F1'}
            >
              <CustomIcon name='compass-3' size={24} color='#8E8E93' />
            </TouchableHighlight>
          </View>
        </View>
        {/* /end bottom bar view */}
      </View>
    );
  }
}

Ignore the numerous console logs that I have there for debugging purposes.

The problem really starts when I try to set the searchState params for range search:

rangeSearch = {
  range: {
    lat: {
      min: minLatitude,
      max: maxLatitude
    },
    long: {
      min: minLongitude,
      max: maxLongitude
    }
  }
}
this.setState({ searchState: rangeSearch });

Without this my code works just fine. In fact, I get this error regardless of what I try to add to the searchState property.

Now, I am no programmer and I know my code is crude, so there might be something stupid simple I'm missing or not getting. But frankly, this is my last resort as I have search everything and I am not finding anything related to this.

What am I doing wrong?

ragunaru avatar Mar 26 '18 20:03 ragunaru

The issue come from the fact that when you want to "control" the searchState you need to always control it. You can't switch between the two modes. In your example the searchState has a null value for his initial state. It means that on the first render InstantSearch will be in a uncontrolled mode. Then when you call setState for updating the searchState the value will switch from null to object. At that moment you are switching between the two modes and the error is thrown. To get rid of this you can initialise the value of the searchState with an empty object. When you are in a full control mode you also need to call setState at every searchState changes.

class App extends Component {
  constructor(props) {
    super(props);

    // ...

    this.state = {
      // ...
      searchState: {}
    };
  }

  onSearchStateChange = searchState => {
    this.setState(() => ({ searchState }));
  };

  render() {
    return (
      <InstantSearch
        searchState={this.state.searchState}
        onSearchStateChange={this.onSearchStateChange}
      >
        ...
      </InstantSearch>
    );
  }
}

If you still have some issue with the code, could you give us a working example? It will helps a lot to understand the full issue. Thanks!

samouss avatar Mar 27 '18 15:03 samouss

Hi @samouss, thanks so much for the reply!

I managed to make my code work without actually using the searchState but using a custom state property and using the <Configure /> widget. I was trying to to a geo search and that required me changing my data schema a little, updating the index and a custom function to set the aroundLatLng property, which is used in the <Configure /> widget.

I also learned about the subtleties of uncontrolled vs controlled from the React documentation: https://reactjs.org/docs/forms.html#controlled-components

Thanks again!

Closing this now since not really to do with Algolia or instantsearch.

ragunaru avatar Mar 27 '18 20:03 ragunaru