0

I am trying to understand an error that I have and that I do not understand. I have this array:

Array [
  Object {
    "cost": 0,
    "created_at": "2020-12-14T15:54:50Z",
    "custom_fields": Object {
      "_161_": "4137",
      "_162_": "48",
      "_163_": "10926",
      "_164_": "0",
      "_165_": "FLY",
      "_166_": "2020-12-14T14:54:37.737Z",
      "_167_": "2020-12-31T14:54:37.737Z",
      "_168_": "0",
      "_171_": "0",
      "_300_": "412:00",
      "_301_": "45.725556|5.081111",
      "_302_": "-27.7078990936|-67.0951004028",
      "_303_": "Lyon Saint-Exupéry Airport",
      "_304_": "Londres/Belén Airport",
      "_310_": "60",
    },
    "description": "",
    "family_id": 0,
    "id": 1061,
    "incl_tax": 0,
    "is_visible": 1,
    "name": "Lyon Saint-Exupéry Airport (14/12/2020 à 15:54) > Londres/Belén Airport (31/12/2020 à 15:54)",
    "photo": "",
    "quantity": 0,
    "reference": "",
    "stock_status": "1",
    "tax_rate_id": 0,
    "unit": "",
    "updated_at": "2020-12-14T15:54:50Z",
    "weight": 0,
  },
  Object {
    "cost": 0,
    "created_at": "2020-11-15T01:38:08Z",
    "custom_fields": Object {
      "_161_": "1373",
      "_162_": "30",
      "_163_": "4680",
      "_164_": "0",
      "_165_": "FLY",
      "_166_": "2020-11-21T00:37:00.000Z",
      "_167_": "2020-11-29T00:37:00.000Z",
      "_168_": "0",
      "_171_": "0",
      "_300_": "190:00",
      "_301_": "43.6539083949|-79.65785399079999",
      "_302_": "-22.285699844399996|-62.7136993408",
      "_303_": "Tarten Heliport",
      "_304_": "Santa Victoria Airport",
      "_310_": "-480",
    },
    "description": "",
    "family_id": 0,
    "id": 896,
    "incl_tax": 0,
    "is_visible": 1,
    "name": "Tarten Heliport (2020-11-21 at 16:37) > Santa Victoria Airport (2020-11-29 at 16:37)",
    "photo": "",
    "quantity": 0,
    "reference": "",
    "stock_status": "1",
    "tax_rate_id": 0,
    "unit": "FLY",
    "updated_at": "2020-11-15T01:38:08Z",
    "weight": 0,
  },
]

It's an array test with 2 products inside (flights) I'm trying to access the filenames, so "name", I don't understand at all why my call returns 'undefined' in console.log when I do

console.log(this.state.name)

I initialize my data in the initListData function, I update the state here so that the name gets the names from my array, I load this function from componentWillMount and then I call the names in my autocomplete.

can someone help me figure out what is wrong, and where i am making the mistake? I need constructed explanations please, there I have a real need for understanding. Thanks for any leads or help.

Full code :

import React, { Component } from "react";
import {
  View,
  Text,
  StyleSheet,
  Button  
} from "react-native";
import styles from '../../../assets/styles';
import * as Permissions from "expo-permissions";
import { getProducts } from '../../../src/common/Preferences';
import { Camera } from 'expo-camera';
import i18n from '../../../src/i18n';
import shortid from "shortid";
import {Autocomplete} from "react-native-dropdown-autocomplete";

class Tickets extends Component {
  constructor(props) {
    super(props);
    this.state = {
      Press: false,
      hasCameraPermission: null,
      name: '',
      lastScannedUrl:null,
      eventSelected: false, 
      displayArray: []      
    };
  }
   initListData = async () => {
    let list = await getProducts(1);
   
    if (list) {
      this.setState({
        displayArray: list,
        name: list.name
      });      
    }
    console.log('name dans initListData =', list.name)
  };

  async UNSAFE_componentWillMount() {
    this.initListData();
    console.log('name dans le state =', this.state.name)
};

  componentDidMount() {
    this.getPermissionsAsync(); 
  }

  getPermissionsAsync = async () => {
    const { status } = await Permissions.askAsync(Permissions.CAMERA);
    this.setState({ hasCameraPermission: status === "granted" });
  };

  handleBarCodeScanned = ({ type, data }) => {
    this.setState({ Press: false, scanned: true, name: data });
    this.props.navigation.navigate('ProductDetails', {name : parseInt(this.state.state.name)})
  };

  renderBarcodeReader = () => {
    const { hasCameraPermission, scanned } = this.state;

    if (hasCameraPermission === null) {
      return <Text>{i18n.t("scan.request")}</Text>;
    }
    if (hasCameraPermission === false) {
      return <Text>{i18n.t("scan.noaccess")}</Text>;
    }
    return (
      <View
        style={{
          flex: 1,
          ...StyleSheet.absoluteFillObject
        }}
      >   
      <Camera
        onBarCodeScanned={scanned ? undefined : this.handleBarCodeScanned}
        barCodeScannerSettings={[Camera.Constants.Type.qr]}
        style={{flex:1}}
      />
        {scanned && (
          <Button
            title={"Tap to Scan Again"}
            onPress={() => this.setState({ scanned: false })}
            disabled={this.state.selectedItem===null}
          />
        )}    
      </View>
    );
  }
  handleSelectItem(item, index) {
    const {onDropdownClose} = this.props;
    onDropdownClose();

    this.setState({eventSelected: true})
    console.log(item);
  }
  render() {
    const { hasCameraPermission, scanned, Press } = this.state;
    let marker = null;

    const {scrollToInput, onDropdownClose, onDropdownShow} = this.props;

 //console.log('displayArray', this.state.displayArray, 'name', this.state.name)

    return (
      <View style={{flex:1}}>         
        <View style={{width: "100%", zIndex: 100}}>                         
          <Autocomplete
            key={shortid.generate()}
            containerStyle={{margin: 0, padding: 0, borderBottomColor: 'transparent',}}
            inputStyle={{ width: '80%', borderWidth: 1, backgroundColor: '#FFF', opacity: 0.9, borderColor: '#F78400'}}
            placeholder={i18n.t("tickets.event")}
            placeholderColor="#F78400"
            pickerStyle={styles.autocompletePicker}
            scrollStyle={styles.autocompleteScroll}
            scrollToInput={ev => {}}
            handleSelectItem={(item, id) => this.handleSelectItem(item, id)}
            onDropdownClose={() => onDropdownClose()}
            onDropdownShow={() => onDropdownShow()}              
            data={this.state.name}
            minimumCharactersCount={2}
            highlightText
            valueExtractor={item => item.name}
            rightContent
            rightTextExtractor={item => item.properties}
          />          
        </View>
        {this.state.eventSelected ? (
          <View>
          {this.renderBarcodeReader()}
          </View>
          ) : (
          <Text style={{ top: '50%', zIndex:100, color: 'red', fontStyle: 'italic', fontSize: 18}}>{i18n.t("tickets.warning")}</Text>
            )}
      </View>
    );
  }
}
export default Tickets;
Kimako
  • 409
  • 1
  • 4
  • 16
  • 2
    1) Do not use `componentWillMount` but rather use `componentDidMount` - there is almost never a good reason to use the `componentWillMount` lifecycle function 2) `initListData` is an async function - if you call the function from a non-async function (such as your `componentWillMount`) and do not wait for the promise to resolve (either by `then` or `await`), the state will not be updated yet - because the request for the data is still running. – nbokmans Jan 07 '21 at 09:48
  • 1
    https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call this question describes your problem but in a more generalized way. – nbokmans Jan 07 '21 at 09:50
  • Thanks for your answer. I found the problem, it's a little bit different of wat you explained but you help a lot, thanks – Kimako Jan 07 '21 at 16:39

0 Answers0