Retrieve new data upon each screen entry

After running a query and rendering items via the UserList component, I use a button in the UserList to run a mutation for deleting an item. The components are linked, so passing the deleteContact function and using refetch() within it ensures that when a user is deleted, the UI is automatically updated.

However, another component called AddContact is not directly linked to the Whitelist component. So when a new user is added and I return to the Whitelist screen, the UI is not updated to show the newly added user. Is there a way to call refetch() every time the Whitelist screen is revisited?

export const Whitelist: React.FunctionComponent = (props) => {

  // useEffect(() => {
  //   refetch()
  // }, []);

  const [deleteUserRelationMutation] = useDeleteUserRelationMutation({
    onCompleted: (index: number) => {
      refetch();
      Alert.alert('Contact Deleted');
    },
    onError: _onDeleteUserRelationError
  });

  const onDeleteContact = (relationId: number) => {
    deleteUserRelationMutation({
      variables: { id: relationId}
  })
  };

  const { loading, error, data, refetch } = useUsersQuery({
    variables: {
      where: { id: 1 },
    },
  });

  return (
    <SafeAreaView style={{ flex: 1 }}>
      <Container style={{ flex: 1, alignItems: 'center' }}>
<Item style={styles.addToWhitelist}>
          <Icon name="add" onPress={() => navigation.navigate('AddContact')} />
          <Text >Add contact</Text>
        </Item>
        <ContactList data={data} onDeleteContact={onDeleteContact}></ContactList>
      </Container>
    </SafeAreaView>
  );
};
export const ContactList: React.FunctionComponent<UserProps> = ({ data, onDeleteContact }) => {

  if (!data) return null;
  return (
    <View style={styles.users}>
    {data.users.nodes[0].userRelations.map(
      (item: { relatedUser: RelatedUser, type: RelationType, id: number}) => {
        const userName = item.relatedUser.firstName.concat(' ').concat(item.relatedUser.lastName);
        return (
          <View style={styles.item} key={item.id}>
              <View style={styles.nameNumber}>
            <Text style={styles.userName}>{userName}</Text>
            </View>
            <View style={styles.deleteButtonContainer}>
              <Button
                onPress={() => onDeleteContact(item.id)}
                >
              </Button>
            </View>
          </View>
        );
      },
    )}
  </View>
  );
};

My attempts to call refetch in useEffect were successful when navigating from the homepage to the whitelist screen. However, revisiting the whitelist after adding a contact from the add contact screen did not update the UI.

I also tried using this in Whitelist:

useFocusEffect(
  React.useCallback(() => {
    console.log('refetching data');
    refetch();
  }, [])
);

The console.log('refetching data'); message appears each time I return to the screen, indicating that the refetch is triggered. However, the UI remains unchanged, suggesting that the refetch may not be functioning as expected.

Answer №1

To keep the users list page updated, you have the option to configure the fetchPolicy in the useUsersQuery hook as either cache-and-network or network-only.

cache-and-network

When using cache-and-network, Apollo will initially display cached data and simultaneously make a network call in the background to update the cache. Once the response is received, the cache is updated triggering a re-render of the component displaying the user list.

Advantages: No loader displayed, offering a quick site experience.

Disadvantages: Potentially showing outdated data until the cache is refreshed (depends on query resolution speed).

This fetch policy is ideal for pages where data changes infrequently, like user lists with minimal additions or deletions.

network-only

With network-only, Apollo always fetches data from the network and does not store it in the cache.

Advantages: Ensures real-time data display.

Disadvantages: Requires a loading indicator during network requests, potentially giving a slower site perception.

If your app frequently adds or deletes users, this fetch policy guarantees up-to-date information at all times.

For more information on fetch policies, refer to the official documentation: https://www.apollographql.com/docs/react/api/react-apollo/#optionsfetchpolicy

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Looking for subsequence in dropdown choices with no assigned values

I need assistance with searching for a specific substring within text that is fetched from options generated by MySQL. How can I retrieve the selected option's text value in order to search for my desired substring? $(document).ready(function() { ...

Exploring the usage of array map parameters in rxjs 6 when combined with withLatestFrom

Prior to Rxjs 6, we were able to achieve the following: interface TypeA { payload: any; } source$.pipe( withLatestFrom(source2$, (source1: TypeA, source2: TypeB) => ({ payload: source1.payload, source2 }) ), ) In the resultSelector method ...

Vue component architecture

Just started exploring Vue last night, so the answer might be obvious. I came across components with this layout: <template> <Slider v-model="value"/> </template> <script> import Slider from '@vueform/slider' ...

Achieve automated zooming out using highcharts-ng through code

Currently, I am using Highcharts-ng as seen on https://github.com/pablojim/highcharts-ng Upon inspecting the source code, I have noticed some interesting functionalities in the directive utilizing scope.$on which I can leverage for broadcasting. One examp ...

Newbie React Developer Struggling to Implement Material-UI Example in React Project, State Functioning Differently from Hooks

I am currently in the early stages of learning React and trying to create a form for a project management web application. For this, I am using material-ui library. I referred to one of the select box component examples from the material-ui documentation ...

Updating the background image without having to validate the cache

I have implemented a basic image slideshow on my website using a simple Javascript function. The function runs every 5 seconds to update the CSS "background-image" property of a div element. While it is functional, I've noticed that each time the func ...

What is the reason behind the unnecessary requirement of adding {...props} when passing them to a component in a React router?

Recently, I delved into learning React and encountered a puzzling issue while following a course. To gain clarity, I decided to experiment with it separately, but the confusion remains unresolved. While researching, I discovered that when utilizing a Rout ...

Error message "Encountered an unknown type 'ForOfStatement' when attempting to execute an npm library"

Currently, I am in the process of integrating the PhotoEditor SDK library into my Ruby on Rails project. To achieve this, I have been meticulously following the installation guidelines provided in the official documentation. However, during the setup proce ...

Is there any more Angular code to be bound using ng-bind-html or ng-bind?

Hey there! Just a quick Angular inquiry: <div class="_minimal_size margin_10_middle"> <div class="_50 espaciado_0_20"> <p ng-bind-html="eirana_knows.feedback"></p> </div> <br class="clear"/> </div ...

Synchronize two div elements with JavaScript

The demonstration features two parent divs, each containing a child div! The first parent div's child div is draggable and resizable using JQueryUI. There are events for both dragEnd and resizeEnd associated with this div. The goal is to synchronize ...

Check for the presence of a horizontal scrollbar on the page for both computer and mobile devices

Is there a way to determine if a web page has a horizontal scrollbar using jQuery or pure JavaScript? I need this information to dynamically change the css of another element. I initially tried function isHorizontalScrollbarEnabled() { return $(docum ...

Please provide either a render prop, a render function as children, or a component prop to the Field(auto) component

While working on my project and implementing an Auto complete feature using final-form, I encountered the following error: Must specify either a render prop, a render function as children, or a component prop to Field(auto) In order to resolve this issue ...

Guide to executing a fetch request prior to another fetch in React Native

I am currently working on a project using React Native. One issue I have run into is that all fetch requests are being executed simultaneously. What I actually need is for one fetch to wait until the previous one has completed before using its data. Speci ...

Is there a peer dependency issue with Node and React?

Currently, I am attempting to utilize a codebase that I discovered while reading an online article. The code can be found at: https://github.com/kangzeroo/Kangzeroos-AWS-Cognito-Boilerplate You can access the package.json file here: https://github.com/kan ...

looking to implement auto-scroll feature in flatlist using react native

I'm attempting to implement auto-scroll functionality in my FlatList, but I'm encountering a problem where the list does not scroll automatically. Additionally, whenever I try to manually scroll, it reverts back to index 0 every 5 seconds. Below ...

Obtaining response object when encountering 401 error in AngularJS

I am currently working with Angular 1.6.4, Express 4.15.2, and express-session. My goal is to identify whether a user is unauthorized to access a specific route by checking for the existence of the req.session.user parameter. If the user is not authorized, ...

Tips for updating multiple bundled javascript files with webpack

I am working on a straightforward app that requires users to provide specific pieces of information in the following format. Kindly input your domain. User: www.google.com Please provide your vast URL. User: www.vast.xx.com Select a position: a) Bottom ...

What is the best approach to add spacing between a user icon and the username using Material UI?

As someone who is still learning about material UI, I've managed to create a User icon and User name. However, I'm struggling to add space in between them. Despite trying p={1} and m={1}, I haven't been successful. Could anyone offer some gu ...

Cypress is having trouble loading a particular URL

I'm encountering a timeout error while trying to load a specific URL using Cypress. Even after setting the page load time to 2 minutes, the issue persists. Interestingly, general URLs like https://www.google.co.nz/ load without any problems. it(' ...

Set up global variables for components to access

Currently, I am working on a Laravel 8 project with vue-sweetalert2 integration. My goal is to set up the Toast behavior once and then be able to call it within various components. At the moment, my code looks like this: /js/components/Mypage.vue <scr ...