useState with array - React Native

Asked

Viewed 3,173 times

1

Good evening. I am learning the Hooks and would like help to solve the problem of updating the useState value from an array. I have the code to follow:

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

const Jantar = () => {
  const opcoes = ['Hamburger', 'Chachorro-quente', 'Lasanha', 'Strogonoff'];
  const [comidas, setComidas] = useState(opcoes[0]);

  const onPress = () => {
    setComidas(comidas => comidas + 1);
  }
  
  return (
    <>
      <Text style={styles.text}>Hoje você vai jantar: {comidas} </Text>
      <TouchableOpacity style={styles.botao}>
        <Text style={styles.text} onPress={onPress} >Escolher comida</Text>
      </TouchableOpacity>
    </>
  );
}

export default function App() {
  
  return (
    <View style={styles.container}>
      <Jantar />
    </View>
  );
}

I have an array of foods and a text field that says which food the person goes to dinner. Each click on the button should update the text field with the next item of the food array. I am unable to update the text field with the onPress function. By my analysis, I need to link, somehow, the variable "food" - which initializes with the first item of the food array - with the array "options". I don’t know how to do.

1 answer

0


You’re doing it wrong, you’re not passing on the options of array and yes by concatenating the text of the first item of array with a value 1, and has to make another state variable where this will store the position to show an option and with this position update with useEffect show the other value contained in array, example:

function App() {
  const opcoes = [
    'Hamburger', 
    'Chachorro-quente', 
    'Lasanha', 
    'Strogonoff'
  ];

  const [position, setPosition] = React.useState(0); // primeiro item do array
  const [comidas, setComidas] = React.useState(''); // estado inicial

  const onPress = () => {
    const pos = position + 1 === opcoes.length 
      ? 0 
      : position + 1;
    setPosition(pos);
  }

  React.useEffect(() => {
    setComidas(opcoes[position]);
  }, [position]);
  return (
    <div>
      <p>{comidas}</p>
      <p><button onClick={onPress}>Próximo</button></p>
    </div>
  )
}
 ReactDOM.render( <App/> , document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.9.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.9.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>

  • Thank you Virgil. You’ve helped so much.

  • @Césaraugusto if your question is answered tick

Browser other questions tagged

You are not signed in. Login or sign up in order to post.