Jake
Jake

Reputation: 120

My component is animating after page load when the data is loaded in the useState

I am using useState() to load some data before the component is mounted.

  const [leaderboardData, setLeaderboardData] = useState([]);
  const [featuredSelectedItem, setSelectedItem] = useState({});
  useEffect(() => {
    let dummyData = [
      ..someData
    ]
    //Order based on standings
    dummyData.sort((a, b) => {
      return a.current_season_standing - b.current_season_standing;
    });

    dummyData[0].active = true;
    setSelectedItem(dummyData[0]);
    setLeaderboardData(dummyData);
  }, []);

My component is wrapped in a Transition group.

     <div className="d-flex h-100 home_container">
      <TransitionGroup className="p-5 flex-1 home_selected_user">
        <SwitchTransition>
          <CSSTransition
            key={featuredSelectedItem.id}
            timeout={500}
            classNames="featuredItem"
          >
            <div>
              <img src="https://via.placeholder.com/150" alt={featuredSelectedItem.name} />
              <h1>{featuredSelectedItem.name}</h1>
              <p>Rank: {featuredSelectedItem.current_season_standing}</p>
              <p>Country: {featuredSelectedItem.country}</p>
              <p>Handicap: {featuredSelectedItem.handicap}</p>
              <p>Wins: {featuredSelectedItem.wins}</p>
              <p>View Player Profile</p>
            </div>
          </CSSTransition>
        </SwitchTransition>
      </TransitionGroup>
      <div className="home_leaderboard p-4 flex-1">
        <Leaderboard activeHandler={activeLeaderboardHandler} data={leaderboardData}></Leaderboard>
      </div>
     </div>

On page load the component loads with no data then animates once the data is loaded onto the component. My goal is for the data to be loaded on the component before the page is loaded so the transition does not trigger?

Upvotes: 2

Views: 339

Answers (1)

Joseph D.
Joseph D.

Reputation: 12174

My component is animating after page load when the data is loaded in the useState

That's because useEffect() will be run after every render. Inside your useEffect() is where you have setSelectedItem().

My goal is for the data to be loaded on the component before the page is loaded so the transition does not trigger?

If you want to have it before, pass the data as props. Then use a conditional render using featuredSelectedItem.

function SomeComponent(props) {
  // initialize using props
  const [featuredSelectedItem, setSelectedItem] = useState(props.data);

  return (
    featuredSelectedItem.length > 0 &&
      <TransitionGroup>...</TransitionGroup>
  )
}

// Usage:
const dummyData = [...someData]

// pass dummyData as prop
<SomeComponent data={dummyData} />

Upvotes: 2

Related Questions