0
votes

I've been trying to save an asyncstorage item, on touchableopacity onPress, then navigate to a react-native-camera screen.

Problem is: Camera screen get blank. I got the following error: Warning: Cannot update during an existing state transition (such as within 'render' or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are anti-pattern, but can be moved to 'componentWillMount'.

Warning points to lines 27, 36 and 41 (at AddParameters class)

Here is the code:

AddParameters.js

import React, { Component } from 'react';

import {
  Text,
  AsyncStorage,
  View,
  TouchableOpacity,
} from 'react-native';

class AddParameters extends Component {
  constructor() {
    super()
    this.state = {
      localIds: [
        "data1",
        "data2",
        "data3",
        "data4",
        "data5",
        "data6"
      ],
    }
  }

  renderScreen = () => {
      return (
            <TouchableOpacity onPress={this._AddParameter(this.state.localIds[0])}>
              <Text>Click Me</Text>
            </TouchableOpacity>
      );
  }

  _AddParameter = (ParameterId) => {
    const { navigate } = this.props.navigation;
    AsyncStorage.setItem("myparam", ParameterId);
    navigate("CameraScreen");
  }

  render() {
    return (
      this.renderScreen()
    );
  }
}



export default AddParameters;

CameraScreen.js

'use strict';
import React, { Component } from 'react';
import {
  AppRegistry,
  Dimensions,
  StyleSheet,
  Text,
  View,
  Image,
  AsyncStorage,
} from 'react-native';
import Camera from 'react-native-camera';

class CameraScreen extends Component {

  constructor(props) {
    super(props);
    this.state = {
      mystate: '',
    };
  }

  renderCamera = () => {
    return (
      <Camera
        ref={(cam) => {
          this.camera = cam;
        }}
        style={stylesCamera.container}
        aspect={Camera.constants.Aspect.fill}>
      </Camera>
    );
  }

  render() {
    return (
      this.renderCamera()
    );
  }
}

const stylesCamera = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "transparent",
  },
});

export default CameraScreen;

Any explanation would be helpfull. Thanks in advance.

1

1 Answers

1
votes

On your AddParameters file try changing this:

<TouchableOpacity onPress={this._AddParameter(this.state.localIds[0])}>

To:

<TouchableOpacity onPress={() => this._AddParameter(this.state.localIds[0])}>