0

I'm creating a single page application on an internal UI. A menu appears on the left of the screen (CollectionsInventory), which contains Links generated from an API call, and on the right, the resulting object (a Collection) is shown in his component. The prop is passed through a url-parameters. I'm also using a Grid component from patternfly4 to manage the UI. This is what it looks like:

<Grid hasGutter>
  <GridItem span={3}>
    {data != null ?
      <CollectionsInventory collections={data[0].collections}/>
    :
      <React.Fragment>
        <Spinner />
      </React.Fragment>
    }
  </GridItem>
  <GridItem span={9}>
    <Router primary={false}>
      <React.Fragment path="/" />
      <Collection path="collection/:collectionName" />
    </Router>
  </GridItem>
</Grid>

Here's the problem; I can make a collection appear by clicking on the corresponding link, or accessing it directly (useful if, say, a user wants to access a bookmark he has of his favorite collection). But then, the collection is stuck there. Whenever I click on a new link, nothing changes. Maybe because it's on the same path? Is there a way to make a link trigger a re-render? Or am I not using the correct components since the menu with the links is outside the router?

In CollectionsInventory, the links are shown in a table, and are generated from a collection name like so:

const defaultRows = collectionList.map( collection => {
  const collectionLink=`collection/${encodeURI(collection.name)}`

  return {
    cells: [
      {
        title:
          <Link to={collectionLink}>
            {collection.name}
          </Link>,
        name: collection.name
      },
      collection.resourceType,
      collection.size
    ]
  }
});
Alexis Lessard
  • 553
  • 6
  • 7

1 Answers1

0

The problem was that my Collection component didn't re-render when the collectionName prop was updated. I tough the react component would re-render whenever we changed the props, but that apparently wasn't the case. So I added an effect with props.collectionName to relaunch the apiFetch process whenever it changes, and Voila! The Collection component updates whenever I select a new link.

Bonus: To be exact, the fetchApi method I'm using is a callback, which gets modified everytime props.collectionName is modified. Here's the shorten version:

const Collection = ({ collectionName }) => {
  const fetchData = useCallback(()=>{
    const apiPath = `/collection/${collectionName}`;
    /* do stuff to retrieve the data and set it in the state, or handle errors*/
  },[collectionName]);

  useEffect(()=>{
    fetchData();
  },[fetchData]);

  return(
   /*The actual content*/
  );
};
Alexis Lessard
  • 553
  • 6
  • 7