Ilierette
Ilierette

Reputation: 11

Pass value from map to state

//It's working now - updated code

I'm working on my own autocomplete component because I have problem with passing firebase data to a ready one.

The whole mechanism is working good but I have problem with passing values after getting user input

I'm setting initial state with those values

const INITIAL_STATE = {
 allChars: [],
 suggestions: [],
 value: ""
};

Then in autocomplete class i'm loading all users from database

loadData(){
 let self = this;
 let characters = firebase.firestore().collection("users");
 characters.get().then((querySnapshot) => {
 querySnapshot.forEach((doc) => {
    let document = doc.data();
    self.setState(({allChars})=>({
      allChars: [
        ...allChars,
        document
      ]        
    }))
  });
 });
}

Here is my getSuggestions function. It is firing on input change

getSuggestions = event => {
 const {value, suggestions} = event.target;
 this.setState({
   value: value,
   suggestions: []
 })
 let suggest = [];

 this.state.allChars.map((allChars) => {
 if(value.length > 1 && allChars.name.toLowerCase().includes(value.toLowerCase())){
    suggest.push (
      allChars.name
    );
  }
 })
 this.setState({
  suggestions: suggest
 })
}

In render I just put {sugestions}
But in {suggestions} I get rendered only one name. one
But when I console.log it - I get two names two
There should be two.

I tried to set state in this function like in loadData(), but I still get only one value.
Is there other way to get both values into DOM

Full code can be found here: https://github.com/Ilierette/react-planner/blob/master/src/component/elements/Autocomplete.js

Upvotes: 1

Views: 536

Answers (1)

Mehrnaz.sa
Mehrnaz.sa

Reputation: 386

I think the reason you are just seeing one element each time your components re-render is that in your map function on your allChars array, when you want to update the suggestions in your state, you are setting just the name each time as a new array while you should update the existing array in your state, so your code should be:

this.setState({
    suggestions: [...this.state.suggestions, allChars.name]
})

Upvotes: 1

Related Questions