Search code examples
reactjsreact-nativegraphqlapollo

Update state when returning to previous page


I'm getting a description from a query call which is showing on the page "profile". When the user wants to edit this description they go to another page called "editProfile". When they are done editing they can press submit which will change the description on the server. My problem is that when I return to the "profile" page the description is not updated in the UI. How do I best fix this? With a hook or some sort of state management like redux? Thanks in advance

function Profile({ navigation }: ProfileStackNavProps<"Profile">) {
  const { loading, error, data } = useQuery(GET_DESCRIPTIONS_FROM_ID);
  const [description, setDescription] = useState(data.profiles[0].description);

  return (
     <Text>{description}</Text>
     //bunch of other code
     <Button
          onPress={() => {
            navigation.navigate("EditProfile", { description });
          }}
        >

  )
}

function EditProfile({ route }: ProfileStackNavProps<"EditProfile">) {
  const [text, setText] = useState(route.params.description);
  const [editDescription, { loading, error }] = useMutation(EDIT_DESCRIPTION);
  return (
    <Center>
      <TextInput onChangeText={setText} value={text} editable={true} />
      <MyButton
        title={"Save"}
        onPress={() => {
          editDescription({
            variables: { description: text },
          });
        }}
      />
    </Center>
  );
}

Solution

  • when navigate to EditProfile, you pass a callback function like this:

    <Button
              onPress={() => {
                navigation.navigate("EditProfile", { description,cb:(newDes)=>{setDescription(newDes)} });
              }}
            >
    

    then, when you finish edit, call the function you pass:

    route.params.cb(newDes)