B
B
broke2022-02-12 12:53:07
css
broke, 2022-02-12 12:53:07

How to control ComponentWillUnMount on UseTransition React Spring?

Good afternoon! I'm using the React Spring library, namely the UseTransition hook to animate page transitions.
Below is the code for wrapped Routes for animation:

export const AllRoutes = () => {
    const location = useLocation()
    const transitions = useTransition(location, {
        from: {
            opacity: 0,
            transform: 'translate3d(100%,0,0)',
            
        },
        enter: {
            opacity: 1,
            transform: 'translate3d(0%,0,0)'

        },
        leave: {
            opacity: 1,
            transform: 'translate3d(-100%,0,0)'

        },
    })

   return(
       transitions((props, item) => (
       <div style={{position: "absolute", left: '0', right: '0',}}>
            <animated.div style={{ ...props}}>
                <Routes location={item.pathname}>
                    <Route path="/pokemons/" element={<PokemonListPage/>}/>
                    <Route path="/pokemons/:id" element={<PokemonPage/>}/>
                    <Route path="/favorites" element={<FavoritePage/>}/>
                    <Route path="/search" element={<SearchPage/>}/>
                </Routes>
            </animated.div>
        </div>
        ))
    ) 
}

Animation is applied, everything is fine. But in one of the components, I use ComponentWillUnMount, which clears the entire data store for this page
export const PokemonPage = () => {
    let {id} = useParams<keyof myParams>() as myParams;
    const dispatch = useAppDispatch()
    const {isLoading, isError} = useAppSelector(state => state.pokemonReducer)

    useEffect(() => {

        dispatch(isFetchingPokemon(id))
        console.log('mounted')
        return () => {
            dispatch(clearPokemon())
            console.log('unmounted')

        }
    }, [id, dispatch])
    
  
    if(isError){
        return(
            <Container>
                    <Error/>
            </Container>
        )
    }

    return (
        <Container >
            <Section>
               {isLoading ? <PageLoader/> : <Pokemon id={id}/>}
            </Section>
        </Container>
        
    )
}


The bottom line is that due to the transition of the animation (opacity + transform), the lifecycle hook does not work as it should. When navigating to a PokemonPage (just another Pokemon), it does a ComponentDidMount on the new data, and then does a ComponentWillUnMount that was delayed.
How to fix this problem? Maybe someone else has experienced something similar!

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question