principemestizo3
principemestizo3

Reputation: 191

React Native useState not working on a AsyncStorage fuction

My code is the following:

function ArScreen({ navigation }) {
  const [open_tabLugar, setOpen_tabLugar] = useState(false);
  const [titulo, setTitulo] = useState('');

  const updateAsyncStorage = async () => {
    AsyncStorage.getItem('data')
        .then((res) => {
        //console.log({ res : JSON.parse(res) });
        console.log(JSON.parse(res).open_tabLugar);
        console.log(JSON.parse(res).titulo);

        setOpen_tabLugar(JSON.parse(res).open_tabLugar);
        setTitulo(JSON.parse(res).titulo);

        console.log(titulo);
        console.log(open_tabLugar);


    }); 
}

useEffect(() => {

    updateAsyncStorage()

    const interval=setInterval(()=>{
      updateAsyncStorage()
     },10000)
     return()=>clearInterval(interval)
     
  }, []);

Output:

console.log(JSON.parse(res).open_tabLugar); ====== true
console.log(JSON.parse(res).titulo); ===== hello

after setOpen_tabLugar and setTitulo
console.log(titulo); ===== ""
console.log(open_tabLugar); ===== false

Why does that happen? I am changing the state (or trying to change it), but it doesn't work. What am I doing wrong?

If you notice, I have a bucket that updates every 10 seconds in useEffect. But, that's not the problem, that works fine (in the update I retract myself, that is the problem, only I don't know how to solve it). The problem is in the change of states.

What am I doing wrong?


UPDATE 1:

If I put this:

setTitulo("HEEEEEEEEEEEEY");
console.log(titulo);

Doesn't work, keeps coming up blank.


UPDATE 2:

I think the problem is inside useEffect(() => { Because I just created a button to run updateAsyncStorage manually and it did work.

 <TouchableOpacity 
              style={{width: 50, borderRadius: 50, height: 50, backgroundColor: 'white', alignItems: 'center', justifyContent: 'center'}} 
              onPress={() => updateAsyncStorage()} >
              <Text style={{color: 'black', fontSize: 20, fontWeight: 'bold'}}>Load</Text>
    </TouchableOpacity>

The button does work fine. Yes the state changes. How do I make it work automatically with useEffect or another alternative?


UPDATE 3:

My new code:

const [open_tabLugar, setOpen_tabLugar] = useState(false);
const [tabLugar, setTabLugar] = useState(false);


useEffect(() => {
    AsyncStorage.getItem('data')
        .then((res) => {
        //console.log({ res : JSON.parse(res) });
        console.log(JSON.parse(res).open_tabLugar);
        console.log(JSON.parse(res).tipo);
        console.log(JSON.parse(res).titulo);
        console.log(JSON.parse(res).descripcion);
        console.log(JSON.parse(res).distance);
        console.log(JSON.parse(res).imagen);
        console.log(JSON.parse(res).imagen_1);

        // string to boolean in AsyncStorage 
        setOpen_tabLugar(JSON.parse(res).open_tabLugar);
        setTipo(JSON.parse(res).tipo);
        setTitulo(JSON.parse(res).titulo);
        setDescripcion(JSON.parse(res).descripcion);
        setDistance(JSON.parse(res).distance);
        setImagen(JSON.parse(res).imagen);
        setImagen_1(JSON.parse(res).imagen_1);

        if(open_tabLugar){
          console.log('-------------- OPEN MODAL --------------');
          setTabLugar(true);
          setOpen_tabLugar(false);
          console.log(open_tabLugar);
        }
    }); 
  },[open_tabLugar, tipo, titulo, descripcion, distance, imagen, imagen_1]);


return(
...

<Modal animationType="slide" transparent={true} visible={tabLugar}>
        <View style={styles_modal.modalViewTabL}>

          <TouchableOpacity onPress={() => setTabLugar(!tabLugar)} style={[styles_modal.button, styles_modal.buttonClose]} >
            <Text style={styles_modal.buttonClosetextStyle}>X</Text>
          </TouchableOpacity>

          <Text style={styles_modal.place_description} numberOfLines={7}>
            La Casa de la Cultura es una de las más importantes obras de arte de la ciudad de Madrid.
          </Text>

        </View>
</Modal>

That works halfway, the problem is that it runs infinitely, it has no end. That started when I put: [open_tabLugar, type, title, description, distance, image, image_1]

After I open my modal with setTabLugar(true); I write setOpen_tabLugar(false);

That should prevent it from opening it again, but then again it runs as true, infinitely.


UPDATE 4:

My error is in the following snippet. Since it runs endlessly. If I remove it the loop stops. How do I fix that problem? Remember that I want the modal to open, but not infinitely in a loop.

if(open_tabLugar){
      console.log('-------------- OPEN OPEN OPEN TAB LUGAR --------------');
      setTabLugar(true);
      setOpen_tabLugar(false);
      console.log(open_tabLugar);
}

Upvotes: 2

Views: 99

Answers (1)

Mustafa Kuru
Mustafa Kuru

Reputation: 11

Unfortunately, hooks cannot be used this way. After the set operation is done, the rendering process takes place and the new value you have assigned will then be available. If you have processes that will work according to these values, you should create useEffect for this and give the variable you will use to the dependency part.

For example, you can print the current values in the following way.

useEffect(() => {
     console.log(titulo);
     console.log(open_tabLugar);       
  },
  [titulo, open_tabLugar],
);

You can show it through a real example for better help.

Upvotes: 1

Related Questions