0

When the text value is logged with a button press, it displays the current value (what I'm expecting). The issue is when I use a setInterval to do the same, it logs every previous value. Is this intentional? If it is, how can I avoid this. Thanks.

import React from 'react';
import {Text, View, Button} from 'react-native';

function showText(text){
  console.log(text);
}

export default function App() {

  const [text,textHook] = React.useState("text not set");

  // Log out text every second
  setInterval(()=>{
    showText(text); // Function repeats for every previous value with a setInterval
  },1000);

  return (
    <View>
      <Text>{text}</Text>
      <Button
        title="change text here"
        onPress={()=>{
          textHook("text is changed");
          console.log(text); // Function works as expected with a button press
        }}
      />
    </View>
  );
}
Adam Shaw
  • 11
  • 2
  • Check this link out the same https://stackoverflow.com/questions/53024496/state-not-updating-when-using-react-state-hook-within-setinterval – Meet Majevadiya Aug 03 '22 at 12:53
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Aug 03 '22 at 21:17

1 Answers1

0

You can use useEffect hook. whenever there will change in value of text useEffect will be called and setInterval will start with updated value.

import React, { useEffect, useRef } from "react";
import { Text, View, Button } from "react-native";

function showText(text) {
  console.log(text);
}

export default function App() {
  const [text, textHook] = React.useState("text not set");
  let timer = useRef();
  // Log out text every second

  useEffect(() => {
    timer = setInterval(() => {
      showText(text);
    }, 1000);
  }, [text]);

  return (
    <View>
      <Text>{text}</Text>
      <Button
        title="change text here"
        onPress={() => {
          clearInterval(timer);
          textHook("text is changed");
          //console.log(text); // Function works as expected with a button press
        }}
      />
    </View>
  );
}