Home > front end >  How to clean a state in screen change?
How to clean a state in screen change?

Time:12-02

I'm trying to clean my state when I change the screen, but it's not working on the first attempt, it just works after a few , someone knows how to make it ?

my code :

const FormScreen = ({route,navigation}) => {
  const [FieldForm,setFieldForm] = useState([]);
  const [TypeForm,setTypeForm] = useState([]);
  const isFocused = navigation.isFocused();
       
  useEffect(() => {
    const unsubscribe = navigation.addListener('blur', () => {
      setFieldForm([]);
      setTypeForm([]);
    })
    try {
     // console.log(isFocused, FieldForm.length, TypeForm.length);
      if (isFocused && FieldForm.length > 0 && TypeForm.length > 0) {
        return;
      } else {
        setFieldForm(JSON.parse(route.params.paramKey).message);
        setTypeForm(JSON.parse(route.params.paramKey).tipo);
      }
    } catch (error) {
      console.log('DEU RUIM',error)
    }
    return unsubscribe
  }, [FieldForm, TypeForm]);
          {...}

Would it works if I use callback , if so how can I use then (in this case) ?

CodePudding user response:

Just to be clear, do you want to clear the state when you go back from FormScreen or just clear the state when you move to any other screen from this one?

For back action, your code seems to ok, but you wouldn't be able to check if the state is in fact cleared, since the component is unmounted anyway on back!

As for the focus change scenario, in react-navigation v6, you might want to use the Navigation Events listeners to get the screen focus/blur. Try to change your code as below:

const FormScreen = ({route,navigation}) => {
const [FieldForm,setFieldForm] = useState([]);
const [TypeForm,setTypeForm] = useState([]);
const isFocused = useIsFocused();

useEffect(()=>{
  const unsubscribe = navigation.addListener('blur', () => {
    setFieldForm([]);
    setTypeForm([]);
  });

  return unsubscribe;
})

// This would not be useful anyway
// const backAction = () => {
//   ...
// };  
// useEffect(() => {  
//   BackHandler.addEventListener('hardwareBackPress', backAction);
//   return () =>
//   BackHandler.removeEventListener('hardwareBackPress', backAction);
// }, [FieldForm, TypeForm]); 
  • Related