Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React, while routing, url changes but the ui updates only after page refresh

I’m trying to build a project that uses infinite scrolling to display the user information in the ui taken from an external API. I’ve managed to fetch the data successfully from the API and also apply the infinite scrolling methodology after a lot of googling.

Now, I’m trying to make a dynamical routing work, so basically, when the user clicks on the card containing the user information that I’m getting from the API, It should be able to redirect to its personal page where there’s gonna be even more personal data. So, I’m using routing for that and I managed to do that as well.

In the User.jsx file, I got the personal information about one single user that I get from the API. Also, on this page, I also have a list of this single user’s friends and when I click on those friend’s card, I should be able to redirect to their own personal page. I’ve managed to do that in a way, the functionality works, but nothing changes in the ui unless if I refresh the page after clicking the friend’s card, after that, page displays the user and their personal data correctly. So that’s essentially what I’m trying to fix, when I click on the card of user’s friend list, the url changes immediately from localhost:3000/users/1 to localhost:3000/users/2, but the ui changes only after I refresh the page.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’d appreciate any tips and help I can get, thank you in advance, here’s the
User.jsx

 const params = useParams();
  const [users, setUsers] = useState();
  const [items, setItems] = useState([]);
  const [isFetching, setIsFetching] = useState(false);
  const [page, setPage] = useState(1);

// Getting the single user 
  useEffect(()=>{
    async function fetchData(){
      const res = await axios(`http://sweeftdigital-intern.eu-central-1.elasticbeanstalk.com/user/${params.id}`);
      console.log(res.data);
      setUsers(res.data);
    }
    fetchData()
  },[]);


// Getting the list of friends 
  const fetchData = (setItems, items) => {
    let url =  `http://sweeftdigital-intern.eu-central-1.elasticbeanstalk.com/user/${params.id}/friends/1/20`;
    axios.get(url).then((res) => {
        setItems([...items, ...res.data.list]);
        console.log(res);
      });
   };

// Browsing more friends by changing the page from API
  const moreData = () => {
    let url = `http://sweeftdigital-intern.eu-central-1.elasticbeanstalk.com/user/${params.id}/friends/${page}/20`;
    
    axios.get(url).then(res => {
      setItems([...items, ...res.data.list]);
      setPage(page+1)
      setIsFetching(false)
    });
  }

// infinite scrolling methodology

  const isScrolling =()=>{
    if(window.innerHeight + document.documentElement.scrollTop!==document.documentElement.offsetHeight){
      return;
    }
    setIsFetching(true)
  }
 
useEffect(()=>{
   fetchData(setItems,items);
   window.addEventListener("scroll", isScrolling);
    return () => window.removeEventListener("scroll", isScrolling);
 },[]);


 useEffect(() => {
  if (isFetching){
    moreData();
  }
}, [isFetching]);

  if(!users) return <p>Fetching...</p>

  return (
    <div>
      <div className='container'>
        <img src={users.imageUrl}/>
        <h1 className='info'>Info</h1>
        <div className='card-div'>
          <div className='name-div'>
            <h3 style={{fontWeight:"bold", fontSize:"30px", color:"#FF416C"}}>{users.prefix} {users.name} {users.lastName}</h3>
            <h3 style={{fontStyle:"italic", fontSize:"22px"}}>{users.title}</h3>
          </div>
          <div className='details-div'>
            <h3>Email: {users.email}</h3>
            <h3>Ip Address: {users.ip}</h3>
            <h3>Job Area: {users.jobArea}</h3>
            <h3>Job Type: {users.jobType}</h3>
          </div>
        </div>
        <h1 className='adress'>Address</h1>
        <div className='address-div'>
          <h3 style={{fontSize:"25px"}}>{users.company.name} {users.company.suffix}</h3>
          <div> 
            <h3>City: {users.address.city}</h3>
            <h3>Country: {users.address.country}</h3>
            <h3>State: {users.address.state}</h3>
            <h3>Street Address: {users.address.streetAddress}</h3>
            <h3>ZIP: {users.address.zipCode}</h3>
          </div>
        </div>
      </div>
      <div className='friends-div'><h1 className='friends-h1'>Friends</h1></div>
      <div className="card-container">
      {items.map((user,key) => (
        <Card key={key} id={user.id} prefix={user.prefix} name={user.name} lastName={user.lastName} image={user.imageUrl} job={user.title}/>
       ))}
      </div>
    </div>
  )

>Solution :

You need to add your params.id to the useEffect‘s dependency list in order to know when it should try to update the UI

  useEffect(()=>{
    async function fetchData(){
      const res = await axios(`http://sweeftdigital-intern.eu-central-1.elasticbeanstalk.com/user/${params.id}`);
      console.log(res.data);
      setUsers(res.data);
    }
    fetchData()
  },[params.id]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading