React Native, accessing a single element from an array nested in state

5.6k views Asked by At

how can I access a single element from an array nested in a state like this

state = {
    modal: false,
    post: [
      {
        key: "1",
        title: "A Good Boi",
        des: "He's a good boi and every one know it.",
        image: require("../assets/dog.jpg"),
      },
      {
        key: "2",
        title: "John Cena",
        des: "As you can see, You can't see me!",
        image: require("../assets/cena.jpg"),
      },
    ]
  };
.....
    <MyList.Provider
          value={{
           
          }}
        >
          <FlatList
            data={this.state.post}
            renderItem={({ item }) => (
              <>
                <TouchableOpacity
                  activeOpacity={0.7}
                  onPress={() => this.deleteItem(item)}
                  style={styles.Delete}
                >
                  <MaterialCommunityIcons name="delete" color="red" size={30} />
                </TouchableOpacity>
                <TouchableOpacity
                  activeOpacity={0.7}
                  onPress={() => this.props.navigation.navigate("Edit", item)}
                  style={styles.Edit}
                >
                  <MaterialCommunityIcons
                    name="playlist-edit"
                    color="green"
                    size={35}
                  />
                </TouchableOpacity>
                <Card
                  title={item.title}
                  subTitle={item.des}
                  image={item.image}
                  onPress={() =>
                    this.props.navigation.navigate("Details", item)
                  }
                />
              </>
            )}
          />
        </MyList.Provider>

how can I do this like this.state.post({title}) or some way else?? I need to use this values with context so I can share and change some particular data with between 2 screens. I know to pass data I need to use context or navigation.navigate("route name",item). But if I use navigation I won't able to edit it but how can I pass data in context value from array set, if I do this.state.post it will return whole list and if i do this.state.post[0].title it will return only title of that post. So how can i do this? Please help

3

There are 3 answers

5
vincent O On

You have to indicate the index of the object you’re trying to access in the array. For instance to access the first object in the array you can do this this.state.post[0]

4
vincent O On

below is my solution which follows the logic i think you are trying to achieve. I have used a flatlist Let me know if it helps


import React, { Component } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  FlatList,
} from 'react-native';

export default class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      modal: false,
      post: [
        {
          key: "1",
          title: "A Good Boi",
          des: "He's a good boi and every one know it.",
          image: require("../assets/dog.jpg"),
        },
        {
          key: "2",
          title: "John Cena",
          des: "As you can see, You can't see me!",
          image: require("../assets/cena.jpg"),
        },
      ]
    };
  }

  handleEdit(item) {
    const { post } = this.state;
    const extractIndex = post.findIndex(e => e.key === item.key);
    const newPost = post[extractIndex];

    this.props.navigation.navigate('Edit', { newPost })
    this.setState({ post });
  }

  handleDelete(item) {
    const { post } = this.state;
    const newPost = post.filter(e => e.key !== item.key);
    this.setState({ post: newPost });
  }

  renderItem = ({ item }) => {
  return (
      <View>
        <Text>
          {item.title}
        </Text>
        <TouchableOpacity key={item.key} onPress={this.handleEdit.bind(this, item)}>
          <Text>Edit</Text>
        </TouchableOpacity>
        <TouchableOpacity key={item.key} onPress={this.handleDelete.bind(this, item)}>
          <Text>Delete</Text>
        </TouchableOpacity>
      </View>
    );
  }
  
  render() {
    return (
      <View style={styles.container}>
        <FlatList 
          data={this.state.post}
          renderItem={this.renderItem}
          keyExtractor={(item, index) => index.toString()}
          extraData={this.state}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
});
0
Sayan Dey On

Use .map() function Ex-

var cat_data = categories_list.map(function (item) {

var cat_data = categories_list.map(function (item) {
    return {
      name: item.Name,
      thumb_url: item.PictureModel.ImageUrl,
      cat_id: item.Id.toString(),
    };
  });
  this.setState({
    data: cat_data,      
  });