How can I change state before link works at react-router-dom

Viewed 1170

I have to get information about user before link work and I don't Know how can I do this. It is not all my code but similar. On click I have to get info and then give it to component in which I link to, but link works first and info does not have time to geted.

  const [userId, setUserId] = useState(null);

  const filterUserbyId = (id) => {
    setUserId(id);
  }

    return(
      <Link 
      onClick={()=>filterUserbyId(props.id)}
      to={{
        pathname: `/user/${props.id}`,
        state: {
          userId: userId
        }
      }}>
   )

Also this is the warning but it says exactly that I tell above

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

1 Answers

You have over-complicated such a simple task.

Instead of trying to fetch the data from the database and then pass that fetched data to the new component to which you will redirect to, you could just pass the user id as a URL parameter

return(
  <Link to={`/user/${props.id}`} />
);

In the other component, extract the user id from the URL parameter using the useParams() hook

const { userID } = useParams();

Note: userID is the dynamic route parameter. For the above statement to work, route to this component should be defined as:

<Route path="/user/:userID" component={/* insert component name */}/> 

Once you have the user id, use the useEffect() hook to fetch the data from the database and display it to the user.

useEffect(() => {
   // fetch the data here
}, []);

Alternative Solution - (not recommended)

You could also do it the way originally tried but for this to work, you need to change the Link component to a normal button element and when that button is clicked, fetch the data from the database and then programmatically change the route using the useHistory() hook, passing along the fetched data to the new route.

const routerHistory = useHistory();

const filterUserbyId = (id) => {
  // fetch user data
  ...
  // redirect to another route
  routerHistory.push(`/user/${props.id}`, { state: data });
}

return(
   <button onClick={() => filterUserbyId(props.id)}>
     Button
   </button>
)

I suggest that you don't use this solution because you don't want to wait for the data to be fetched from the database before changing the route. Route should be changed as soon as user clicks and data should be fetched inside the new component.

Related