简体   繁体   中英

React Native Selected item is not reflecting the state to the UI

I am trying to develop a component that should show all ingredients from my data base, but the state has not updated as expected.

variables:

  const image = require('../../assets/backgroundMeal.png');
  const [name, setName] = useState('')
  const [ingredients, setIngredients] = useState([])
  const [recipes, setRecipes] = useState([])
  const [ingredientList, setIngredientList] = useState([{id:null, name:null, isSelected:false}])

The API Call:

useEffect(() => {
    let recipeRequest = 'http://192.168.0.3:3333/report'
    let ingredientsRequest = 'http://192.168.0.3:3333/ingredients'
    recipeRequest = axios.get(recipeRequest)
    ingredientsRequest = axios.get(ingredientsRequest)
        axios.all([recipeRequest, ingredientsRequest])
          .then(axios.spread((...responses) => {
            setRecipes(responses[0].data)
            setIngredientList(responses[1].data)
          }))
          .catch(function (error) {
            console.log('API CALL - recipe/ingredient - error: ', error);
          })
    
  },[ingredientList])

The variable "ingredientsRequest" has all the ingredients.

This is the variable who is join the "isSelected" with the "ingredientList"

  const [allItems, setAllItems] = useState([ingredientList]);
  const selectedIngredient = (item) => {
    let temp = allItems.filter(parentItem => parentItem.id !== item.id)
    item.isSelected = !item.isSelected;
    temp = temp.concat(item);
    temp.sort((a, b) => parseInt(a.id) - parseInt(b.id))
    
    setAllItems(temp)
    console.log('## allItems', allItems)

This is the first Problem, I declared the state with the shape "id" and "name" iguals to null and the useEffect axios call, should update the "setIngredientList" and the "ingredientList" should be updated, but the console.log that I call befor the "return" show that the Object remais with null value to the ID and NAME variable with null value. It should be updated in the axios call I have at the useEffect, why It do not?

Result of the console.log at the "allItems" variable.

Array [ Object { "id": null, "isSelected": false, "name": null, },

Once I click in the Flatlist component, it updated the "isSelected" state correctly, but do not show all the "ingredientList" state, even considering that the "allItems" variable use the useState([ingredientList]), so I think it should have the ingredientList shape, is that right?

<FlatList
  horizontal
  bounces={false}
  data={allItems}
  renderItem={({ item, index }) => (
  <TouchableOpacity key={item.id} onPress={() => selectedIngredient(item, index)}>
    <Card key={index}>
      <Text key={item.title} style={styles.titleText}>{item.name}</Text>
      <Text key={item.title} style={styles.titleText}>{item.isSelected}</Text>
      <Text key={item.title} style={styles.titleText}>{item.isSelected?(
      <Text style={{color: "red"}}>{"Not Selected"}</Text>
      ) : (
      <Text style={{color: "green"}}>{"Selected"}</Text>
      )}</Text>
      <ImageBackground key={item.illustration} source={item.illustration} style={styles.cardImage}> 
      </ImageBackground>
    </Card>
  </TouchableOpacity>
  )
  }
  keyExtractor={(item) => item.index}
/>

can someone help me on it? Thanks a lot.

Try this, It will reflect on UI on selection

const selectedIngredient = (item, index) => {
    const tempAllItems = [...allItems];
    tempAllItems[index].isSelected = !item.isSelected;
    
    setAllItems(tempAllItems);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM