Как удалить определенный элемент списка локально и с сервера после удара в реагировать родной - PullRequest
1 голос
/ 13 марта 2019

// Здесь в моем коде я вызываю 2 APIS 1. (createViewGroup = async () =>) один для получения данных с сервера и установки на инвентаризацию FlatList, id, sensorType,

2 секунды API ("SensorDelt = (rowIndex) =>") призываю удалить конкретный список итераций с сервера, я имею в виду после касания определенного элемента списка, я беру идентификатор no и этот идентификатор ({"password": "admin", "username":"admin", "sensorid": "здесь я должен отправить идентификатор нет"}) отправляю на сервер, и этот идентификатор будет удален.

В моем коде я использую кнопку удаления Swipeout для удаления элемента списка, ноон работает локально, не удаляя с сервера.Пожалуйста, помогите

import * as React from "react";
import {
  View,
  Text,
  TextInput,
  FooterTab,
  Button,
  TouchableOpacity,
  ScrollView,
  StyleSheet,
  ActivityIndicator,
  Header,
  Alert,
  AsyncStorage,
  FlatList
} from "react-native";
import { Table, Row, Rows } from "react-native-table-component";
import { createStackNavigator, createAppContainer } from "react-navigation";
import { SearchBar } from "react-native-elements";

// You can import from local files
//import AssetExample from './components/AssetExample';

// or any pure javascript modules available in npm
import { Card } from "react-native-paper";
import Swipeout from "react-native-swipeout";

class OpenApplianceIssue extends React.Component {
  constructor() {
    super();
    this.state = {
      AbcSdata: null,
      loading: true,
      search: "",
      tableData: [],
      qrData: "",
      selectedPriority: "",
      selectedIssue: "",
      selectedReason: "",
      selectedTriedRestart: "",
      selectedPowerLED: "",
      selectedBurning: "",
      selectedNoise: "",
      rowID: "",
      activeRow: null
    };
    this.setDate = this.setDate.bind(this);
  }

  swipeBtns = [
    {
      text: "Delete",
      type: "delete",
      backgroundColor: "red",
      underlayColor: "rgba(0, 0, 0, 1, 0.6)",
      onPress: () => {
        console.log("Deleting Row with Id ", this.state.activeRow);
        {
          this.deleteNote(this.state.activeRow);
          this.onClickListener("del");
        }
      }
      //onPress:() => this.onClickListener('tag')}
    }
  ];

  removeItem = (items, i) =>
    items.slice(0, i).concat(items.slice(i + 1, items.length));

  deleteNote = rowIndex => {
    //add your custome logic to delete the array element with index.
    // this will temporary delete from the state.
    let filteredData = this.removeItem(this.state.AbcSdata, rowIndex);
    this.setState({ AbcSdata: [] }, () => {
      this.setState({ AbcSdata: filteredData }, () => {
        console.log("Row deleted.", rowIndex);
      });
    });
  };

  setDate(newDate) {}

  _loadInitialState = async () => {
    const { navigation } = this.props;
    const qdata = navigation.getParam("data", "NA").split(",");
    var len = qdata.length;
    const tData = [];
    console.log(len);
    for (let i = 0; i < len; i++) {
      var data = qdata[i].split(":");
      const entry = [];
      entry.push(`${data[0]}`);
      entry.push(`${data[1]}`);
      tData.push(entry);
    }
    this.setState({ tableData: tData });

    console.log(this.state.tableData);
    this.setState({ loading: true });
  };

  // Delete  Sensors ********************

  SensorDelt = rowIndex => {
    //const Sensorid_Data =  this.props.navigation.state.params.item.id;
    let filteredData = this.removeItem(this.state.AbcSdata, rowIndex);
    let ABHI = filteredData//const Sensorid_Data =  this.state.rowIndex;
    .console
      .log("Value Abhi" + filteredData);
    Alert.alert("Value" + filteredData);

    fetch("http:/Dsenze/userapi/sensor/delsensor", {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        password: "admin",
        username: "admin",
        sensorid: filteredData
      })
    })
      .then(response => {
        //console.log(response);
        return response.json();
      })

      .then(res => {
        if (res.success == "true") {
          Alert.alert("Sensor Added");
          this.props.navigation.replace("OpenApplianceIssue");
        } else {
          Alert.alert("Success false");
        }
      });
  };

  handleValueChange(SensortypeId) {
    this.setState({ SensortypeId });
  }

  // Delete sensors ***********************

  onClickListener = viewId => {
    if (viewId == "tag") {
      this.props.navigation.navigate("AddSensors");
    } else if (viewId == "del") {
      //this.props.navigation.navigate('AddSensors');
      this.SensorDelt();
    }
  };

  componentDidMount() {
    //this._loadInitialState().done();
    this.createViewGroup();
  }

  // Get Sensor list ********************************************
  createViewGroup = async () => {
    try {
      const response = await fetch(
        "http://Dsenze/userapi/sensor/viewsensor",
        {
          method: "POST",
          headers: {
            Accept: "application/json",
            "Content-Type": "application/json"
          },
          body: JSON.stringify({
            password: "admin",
            username: "admin",
            startlimit: "0",
            valuelimit: "10"
          })
        }
      );

      const responseJson = await response.json();

      const { sensorData } = responseJson;

      this.setState({
        AbcSdata: sensorData,
        loading: false
      });
    } catch (e) {
      console.error(e);
    }
  };

  clickedItemText(OpenApplianceIssue) {
    this.props.navigation.navigate("Item007", { item: OpenApplianceIssue });
    //Abc =  this.props.navigation.state.params.item.id;
  }

  updateSearch = search => {
    this.setState({ search });
  };
  keyExtractor = ({ id }) => id.toString();
  keyExtractor = ({ inventory }) => inventory.toString();

  onSwipeOpen(rowId, direction) {
    if (typeof direction !== "undefined") {
      this.setState({ activeRow: rowId });
      console.log("Active Row", rowId);
    }
  }

  renderItem = ({ item, index }) => (
    <Swipeout
      style={styles.SwipeBG}
      right={this.swipeBtns}
      close={this.state.activeRow !== index}
      rowID={index}
      sectionId={1}
      autoClose={true}
      // onOpen = {(secId, rowId, direction) => this.onSwipeOpen(rowId, direction)}
    >
      <TouchableOpacity
        style={styles.item}
        activeOpacity={0.4}
        onPress={() => {
          this.clickedItemText(item);
        }}
      >
        {/* //onPress={this.viewNote(item)} >
               > */}

        <Text>Id : {item.id}</Text>
        <Text>Inventory : {item.inventory}</Text>
        <Text>SensorType : {item.sensorType}</Text>
        <Text>TypeName : {item.typeName}</Text>
      </TouchableOpacity>
    </Swipeout>
  );
  //  viewNote =(item) => {
  //    this.props.navigator.push({
  //       title: 'The Note',
  //       component: this.ViewNote,
  //       passProps: {
  //         noteText: item,
  //         noteId: this.noteId(item),
  //       }
  //     });
  //    console.log("View Note Success");
  //  }

  renderSeparator = () => {
    return (
      <View
        style={{
          height: 1,
          width: "86%",
          backgroundColor: "#CED0CE"
        }}
      />
    );
  };

  render() {
    const { loading, AbcSdata } = this.state;
    const state = this.state;

    return (
      <ScrollView>
        <View style={styles.container1}>
          <Button
            full
            rounded
            style={{ fontSize: 20, color: "green" }}
            styleDisabled={{ color: "red" }}
            onPress={() => this.onClickListener("tag")}
            title="Add Sensors"
          >
            Add Sensors
          </Button>
        </View>

        <View style={styles.container1}>
          {this.state.loading ? (
            <ActivityIndicator size="large" />
          ) : (
            <FlatList
              style={styles.ListDATA}
              data={AbcSdata}
              renderItem={this.renderItem}
              keyExtractor={this.keyExtractor}
              extraData={this.state.activeRow}
              ItemSeparatorComponent={this.renderSeparator}
            />
          )}
        </View>

        <View>
          <Text
            style={{ alignSelf: "center", fontWeight: "bold", color: "black" }}
          >
            Inventory Details
          </Text>

          <Table
            borderStyle={{
              borderWidth: 2,
              borderColor: "#c8e1ff",
              padding: 10,
              paddingBottom: 10
            }}
          >
            <Rows data={state.tableData} textStyle={styles.text} />
          </Table>
        </View>
      </ScrollView>
    );
  }
}

export default (OpenApplianceIssue = createStackNavigator({
  Item007: { screen: OpenApplianceIssue }
}));

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    backgroundColor: "#ecf0f1",
    padding: 8
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: "bold",
    textAlign: "center"
  },

  SwipeBG: {
    backgroundColor: "#ffffff",
    marginLeft: 7,
    marginTop: 3
  },
  ListDATA: {
    backgroundColor: "#ffffff",
    marginLeft: 5,
    marginTop: 3
  }
}); 

Спасибо image) "sensorid" : here i have to pass id number ,">

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...