logo
down
shadow

Update selected item from Flatlist in Firebase using React Native


Update selected item from Flatlist in Firebase using React Native

By : stemblestep
Date : November 22 2020, 03:01 PM
it helps some times You are not passing item to any of your function calls, so it is interpreting the parameters as undefined, hence your issue. You need to pass the item through your logic so that the correct firebase path can be accessed. You could also use a state variable but that is another story
Location 1
code :
onRenderItem = (item) => (
<TouchableOpacity onPress={() => {this.showAlert(item)}}>
...
showAlert = (item) => {
Alert.alert(...
{ text: 'Completed?',
        onPress: () => this.goalComplete(item)
    },
    { text: 'Failed?',
        onPress: () => this.goalFailed(item)
    },


Share : facebook icon twitter icon
Highlight a selected item in React-Native FlatList

Highlight a selected item in React-Native FlatList


By : D. Kryvopyshyn
Date : March 29 2020, 07:55 AM
may help you . In place of this.state.selectedItem and setting with/checking for a rowItem.id.value, I would recommend using a Map object with key:value pairs as shown in the RN FlatList docs example: https://facebook.github.io/react-native/docs/flatlist.html. Take a look at the js Map docs as well: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map.
The extraData prop recommended by @j.I-V will ensure re-rendering occurs when this.state.selected changes on selection.
code :
export default class BasicFlatList extends Component {
  state = {
    otherStateStuff: ...,
    selected: (new Map(): Map<string, boolean>) //iterable object with string:boolean key:value pairs
  }

  onPressAction = (key: string) => {
    this.setState((state) => {
      //create new Map object, maintaining state immutability
      const selected = new Map(state.selected);
      //remove key if selected, add key if not selected
      this.state.selected.has(key) ? selected.delete(key, !selected.get(key)) : selected.set(key, !selected.get(key));
      return {selected};
    });
  }

  renderRow = (item) => {
    return (
        <RowItem
          {...otherProps}
          item={item}
          onPressItem={this.onPressAction}
          selected={!!this.state.selected.get(item.key)} />
    );
  }

  render() {
    return(
      <FlatList style={styles.container}
        data={this.state.data}
        renderItem={({ item }) => (
          this.renderRow(item)
        )}
        extraData={this.state}
      />
    );
  }
}


class RowItem extends Component {
  render(){
    //render styles and components conditionally using this.props.selected ? _ : _
    
    return (
      <TouchableOpacity onPress={this.props.onPressItem}>
        ...
      </TouchableOpacity>
    )
  }
}
How to update a single item in FlatList in React Native?

How to update a single item in FlatList in React Native?


By : mikedido
Date : March 29 2020, 07:55 AM
hop of those help? Don't get me wrong, @ShubhnikSingh's answer did help, but I retracted it because I found a better solution to this question, long time ago, and finally I remembered to post it here.
Suppose my post item contains these properties:
code :
{
    postId: "-L84e-aHwBedm1FHhcqv",
    date: 1525566855,
    message: "My Post",
    uid: "52YgRFw4jWhYL5ulK11slBv7e583",
    liked: false,
    likeCount: 0,
    commentCount: 0
}
class Post extends Component {                                                      
  // This determines whether a rendered post should get updated                     
  // Look at the states here, what could be changing as time goes by?               
  // Only 2 properties: "liked" and "likeCount", if the person seeing               
  // this post ever presses the "like" button                                       
  // This assumes that, unlike Twitter, updates do not come from other              
  // instances of the application in real time.                                     
  shouldComponentUpdate(nextProps, nextState) {                                     
    const { liked, likeCount } = nextProps                                          
    const { liked: oldLiked, likeCount: oldLikeCount } = this.props                 

    // If "liked" or "likeCount" is different, then update                          
    return liked !== oldLiked || likeCount !== oldLikeCount                         
  }                                                                                 

  render() {                                                                        
    return (                                                                        
      <View>                                                                        
        {/* ...render other properties */}                                          
        <TouchableOpacity                                                           
          onPress={() => this.props.onPressLike(this.props.postId)}                 
        >                                                                           
          <Icon name="heart" color={this.props.liked ? 'gray' : 'red'} />           
        </TouchableOpacity>                                                         
      </View>                                                                       
    )                                                                               
  }                                                                                 
}                                                                                   
class PostList extends Component {                                                        

/**                                                                                       
 * As you can see, we are not storing "posts" as an array. Instead,                       
 * we make it a JSON object. This allows us to access a post more concisely               
 * than if we stores posts as an array. For example:                                      
 *                                                                                        
 * this.state.posts as an array                                                           
 * findPost(postId) {                                                                     
 *   return this.state.posts.find(post => post.id === postId)                             
 * }                                                                                      
 * findPost(postId) {                                                                     
 *   return this.state.posts[postId]                                                      
 * }                                                                                      
 * a specific post by its "postId", you won't have to iterate                             
 * through the whole array, you can just call "posts[postId]"                             
 * to access it immediately:                                                              
 * "posts": {                                                                             
 *     "<post_id_1>": { "message": "", "uid": "", ... },                                  
 *     "<post_id_2>": { "message": "", "uid": "", ... },                                  
 *     "<post_id_3>": { "message": "", "uid": "", ... }                                   
 * }                                                                                      
 * FlatList wants an array for its data property rather than an object,                   
 * so we need to pass data={Object.values(this.state.posts)} rather than                  
 * just data={this.state.posts} as one might expect.                                      
*/                                                                                        

  state = {                                                                                 
    posts: {}                                                                               
    // Other states                                                                         
  }                                                                                         

  renderItem = ({ item }) => {
    const { date, message, uid, postId, other, props, here } = item
    return (
      <Post
        date={date}
        message={message}
        uid={uid}
        onPressLike={this.handleLikePost}
      />
    )
  }

  handleLikePost = postId => {
    let post = this.state.posts[postId]
    const { liked, likeCount } = post

    const newPost = {
      ...post,
      liked: !liked,
      likeCount: liked ? likeCount - 1 : likeCount + 1
    }

    this.setState({
      posts: {
        ...this.state.posts,
        [postId]: newPost
      }
    })
  }

  render() {
    return (
      <View style={{ flex: 1 }}>
        <FlatList
          data={Object.values(this.state.posts)}
          renderItem={this.renderItem}
          keyExtractor={({ item }) => item.postId}
        />
      </View>
    )
  }
}
get Value of selected item in FlatList. -- React Native

get Value of selected item in FlatList. -- React Native


By : Karam N. Hazim
Date : March 29 2020, 07:55 AM
This might help you Considering @SNT answer and bennygenel comments. I have added this. answer as both of their suggestions requires attention.
code :
 _renderList = ({ item }) => {
    return (
     <TouchableWithoutFeedback onPress={(event)=>this._selectedItem(item.text)}>
        <View style={styles.listContainer}>
            <Image style={styles.listImage} source={item.avatar} />
            <Text style={styles.listText} >{item.text}</Text>
            <Text style={styles.listVal} >{item.val}</Text>
            <Image style={styles.listImage}   source={require('../../resources/icons/MyAccount/arrowright.png')} />
        </View>
     </TouchableWithoutFeedback>
    );

}


<FlatList data={this.state.data} renderItem={this._renderList} />
Only allow one item to be selected in a React Native FlatList

Only allow one item to be selected in a React Native FlatList


By : user3511812
Date : March 29 2020, 07:55 AM
should help you out you don't need new Map() in this case, you just simply want to store a user choice in a variable. For example
code :
const [selected, setSelected] = React.useState(null);
const onSelect = (id) => {
 setSelected(id);
}
<ListTeacher
        id={item.id}
        name={item.name}
        selected={item.id === selected}
        onSelect={onSelect}
 />
How to update a single item in FlatList - React Native

How to update a single item in FlatList - React Native


By : user3631868
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further First of all thanks to @TRomesh for his answer.
Based on that I found a solution for this issue easily
code :
 handleUserLikes = item => {
    this.props.addLikeToPost({
        item_id:item.id,
        user_token:this.state.user_token,
        user_id:this.state.userDetails.id,
      });
  };
const userLike = (state, payload) => {
  console.log('TCL: userLike -> payload', payload.payload);
  console.log('TCL: userLike -> state.postData', state.postData);

  let item = state.postData.find(user => user.id == payload.payload.item_id);
  let local_data = state.postData;
  let isLiked = item.likedUsers.find(
    user => user.id === payload.payload.user_id,
  );
  if (isLiked) {
    local_data = local_data.map(data => {
      if (data.id == payload.payload.item_id) {
        data.likesCount = Number(data.likesCount - 1);
      }
      return data;
    });
  } else if (isLiked == undefined || isLiked == null) {
    local_data = local_data.map(data => {
      if (data.id == payload.payload.item_id) {
        data.likesCount = Number(data.likesCount + 1);
      }
      return data;
    });
  }
  return {...state, postData: local_data};
};
Related Posts Related Posts :
  • How to get text from selected value in a dropdownlist which is js based
  • window is not defined angular universal third library
  • Angularjs ng-repeat stylization depending on previous value
  • Trying to implement Fittext.js
  • Calculate number of match in array Lodash
  • Jquery Smooth Scroll Using Offset.top
  • How to extract data to React state from CSV file using Papa Parse?
  • How to add unique links to google maps markers
  • How to use if condition in a tool bar in java script
  • Ajax filter in django not showing in HTML
  • data collection with Javascript
  • Rotate image on lightbox2 load
  • Prevent body from scrolling when a Pop-Up is open
  • How to copy files that do not need to be compiled in Gulp?
  • Array not assigned to variable? How does this work and what exactly is it doing?
  • Sorting associative array of objects in javascript
  • Changing Icon in Sap.m.tree having CustomTreeItem
  • Merge two array of objects based on a key
  • javascript in css not working
  • Passing only clicked element to onClick function - reactjs
  • React boilerplate doesn't load js files in the index.html
  • is Child service inside child component visible in the Parent component?
  • Check if data attribute value equals a string
  • How to get value of child tag of a button tag
  • How to access subjects of selected mails in Apple Mail using JavaScript?
  • How to get all dynamically set inline-style CSS in jQuery?
  • Error: Module "html" does not provide a view engine (Express)
  • Random Image in <Div> from array
  • Slider with touch function
  • ReactJS Component Architecture Problems / Nested Components or Single Component Manager
  • Javascript: Caching within Closure doesn't work
  • HTM5 Canvas Drawing App: How Do I Select The Color?
  • Assigning Events using HTML DOM
  • html5 getUserMedia() portrait mode
  • How to avoid 'headers already sent' within Promise chain?
  • Get a result from a react native app integrated into an existing android app
  • Why does the value of input field return undefined
  • How to get return object in jquery uploadFile method
  • Javascript string with arguments to single quotes
  • Understanding JS functions syntax (applies to other languages as well, I'm sure)
  • AngularJS Single Page App: Reference Error, ____ is not defined
  • whatwg-fetch new typescript 2.5.3
  • React.js - Array.unshift() not updating array on front-end
  • JavaScript localeCompare don't sort well [ "aaa-1.0", "aaa-1.1", "aaa-1.01", "aaa-11&
  • Mongoose handle validation error in a promise call and Express middleware
  • Building tree array of objects from flat array of objects
  • How to add a progress bar to file upload using javascript and ajax call?
  • JavaScript: is it permitted to override a standard built-in object?
  • Change the current page of an AJAX datatables
  • Array element is undefined even after pushing elements into it
  • onmousemove event not working
  • Chrome-Extension/JavaScript How to make all links on page have no effect?
  • Websocket issue Internet Explorer
  • sessionStorage value becomes null in other tab in AngularJS
  • Split URL from position x to the end in Javascript
  • How to set value of input field with NgIf in Angular 4
  • invalidStateError for second time screenshare on Chrome
  • How do you pass a value to the variable in a xhr.setRequestHeader?
  • I cant start nodemon on my windows 10
  • Nested if else jumps out from the main if else in javascript
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org