react native clear previous page when use previous button from stack navigation

20 Views Asked by At

I have a page with a form, and a button that will take to another route using stack navigation, but when I use the back button, all the inputs remain filled, I wanted to reset all the values, when I click on the button to return from stack navigation.

my router:

import { NavigationContainer } from '@react-navigation/native'
import { createStackNavigator } from '@react-navigation/stack'
import {Home}  from '@/screens/home'
import {Result}  from '@/screens/result'

const Stack = createStackNavigator();

declare global {
    namespace ReactNavigation {
        interface RootParamList{
            Home: undefined;
            Result: undefined;
        }
    }
}

export default function Routes() {
    return (
        <NavigationContainer>
            <Stack.Navigator initialRouteName="Home">
                <Stack.Screen name="Home" component={Home}  options={{headerShadowVisible: false, headerShown: false,}} />
                <Stack.Screen name="Result" component={Result} options={{
                    title: '',
                    headerShadowVisible: false,
                    headerTransparent: true,
                    headerStyle: {
                        backgroundColor: '#e7305b',
                    }}} />
            </Stack.Navigator>
        </NavigationContainer>
    )
}

home component:

import { Image, View, ScrollView, Text } from "react-native"
import { Button } from "@/components/Button"
import { useNavigation } from "@react-navigation/native"
import {ControlledTextInput} from '@/controller/controlled_input'
import { useForm  } from 'react-hook-form'
import { yupResolver } from '@hookform/resolvers/yup'
// import moment from 'moment'
import * as yup from 'yup'

const phoneNumberRules = /^(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?[789]\d{9}$/;

const schema = yup.object({
    name: yup.string().required("Informe o nome do cliente!"),
    phone: yup.string()
    .required("Informe o telefone do cliente!"),
    address: yup.string().required("Informe o endereço do cliente"),
    buy_date: yup.string().required("Informe a data de compra!"),
    weight: yup.number().min(1).required("Informe o peso do casco!"),
    tara: yup.number().min(1).required("Informe a tara!"),
})

export function Home() {
    const { navigate } = useNavigation();
 
    const { 
        control,
        handleSubmit,
        formState: { errors },
    } = useForm({
        resolver: yupResolver(schema),
    });

    const onSubmit = (data: any) => {
        console.log(data)

        navigate('Result')
    };
    

    return (
        <View className="flex flex-1 flex-col space-between bg-slate-700">

            <View className="flex justify-center py-4">
                <View className="flex items-center">
                    <Image  className="mt-10" source={require("@/assets/banner.png")}/>
                </View>
            </View>


            <View className="flex justify-center">
                <ScrollView className="flex flex-col space-between">
                    <View className="flex flex-col space-between px-10 py-2">
                        <ControlledTextInput 
                            control={control}
                            name="name"
                            placeholder="Nome"
                            className={`... ${errors.name ? 'border-2 border-red-800 border-r rounded-lg' : ''}`}
                        />
                        {errors.name && <Text style={{
                            alignSelf: 'flex-start',
                            color: '#ff375b',
                            marginTop: 5,
                        }}
                        >{errors.name.message}</Text>}
                    </View>
                    <View className="flex flex-col space-between px-10 py-2">
                        <ControlledTextInput 
                            control={control}
                            name="phone"
                            placeholder="Telefone"
                            className={`... ${errors.phone ? 'border-2 border-red-800 border-r rounded-lg' : ''}`}
                        />
                         {errors.phone && <Text style={{
                            alignSelf: 'flex-start',
                            color: '#ff375b',
                            marginTop: 5,
                        }}
                        >{errors.phone?.message}</Text>}
                    </View>
                    <View className="flex flex-col space-between px-10 py-2">
                        <ControlledTextInput 
                            control={control}
                            name="address"
                            placeholder="Endereço"
                            className={`... ${errors.address ? 'border-2 border-red-800 border-r rounded-lg' : ''}`}
                        />
                         {errors.address && <Text style={{
                            alignSelf: 'flex-start',
                            color: '#ff375b',
                            marginTop: 5,
                        }}
                        >{errors.address?.message}</Text>}
                    </View>
                    <View className="flex flex-col space-between px-10 py-2">
                        <ControlledTextInput 
                            control={control}
                            name="buy_date"
                            placeholder="Data de Compra"
                            className={`... ${errors.buy_date ? 'border-2 border-red-800 border-r rounded-lg' : ''}`}
                        />
                         {errors.buy_date && <Text style={{
                            alignSelf: 'flex-start',
                            color: '#ff375b',
                            marginTop: 5,
                        }}
                        >{errors.buy_date?.message}</Text>}
                    </View>
                    <View className="flex flex-col space-between px-10 py-2">
                        <ControlledTextInput 
                            control={control}
                            name="weight"
                            placeholder="Peso"
                            className={`... ${errors.weight ? 'border-2 border-red-800 border-r rounded-lg' : ''}`}
                        />
                         {errors.weight && <Text style={{
                            alignSelf: 'flex-start',
                            color: '#ff375b',
                            marginTop: 5,
                        }}
                        >{errors.weight?.message}</Text>}
                    </View>
                    <View className="flex flex-col space-between px-10 py-2">
                        <ControlledTextInput 
                            control={control}
                            name="tara"
                            placeholder="Tara"
                            className={`... ${errors.tara ? 'border-2 border-red-800 border-r rounded-lg' : ''}`}
                        />
                         {errors.tara && <Text style={{
                            alignSelf: 'flex-start',
                            color: '#ff375b',
                            marginTop: 5,
                        }}
                        >{errors.tara?.message}</Text>}
                    </View>
                </ScrollView>
            </View>

            <View className="flex py-4 px-10 justify-center">
                    <Button 
                        label="Enviar formulário"
                        labelClasses="text-indigo-950"
                        onPress={handleSubmit(onSubmit)} 
                    />
            </View>
         </View>
    )
}

result component:

import { Image, View, Text } from "react-native"

export function Result() {

    return (
        <View className="flex flex-1 flex-col space-between bg-slate-700">

        <View className="flex justify-center">
            <View className="flex items-center">
                <Image  className="mt-10" source={require("@/assets/banner.png")}/>
            </View>
        </View>

        <View className="flex flex-1 pt-4">
            <Text>Result</Text>
         </View>

        </View>
    )
}

when i click on the button to navigate to Result page, when i click on back to previous route from stack navigator the inputs continue to be filled with the old values

1

There are 1 best solutions below

0
Tyler Butters On BEST ANSWER

The way that the stack navigator works is by layering screens on top of each other. When you call "navigation.navigate()" it will add on the new screen on top. But the previous screen underneath it is still there. That's why the values are still inputted because nothing has changed.

So when you navigate to the next page, just reset all the values manually. Alternatively you could use a "useFocusEffect" hook to reset the values whenever you come back to that page

const onSubmit = (data: any) => {
    console.log(data)
    //reset data
    navigate('Result')
};

or:

useFocusEffect(
    React.useCallback(()=>{
        //screen is focused, reset data
    },[])
)