kamal11
kamal11

Reputation: 384

useEffect cleanup function does not immediately update data?

How/When does the cleanup function update data?

I am clearing the state in cleanup fn but it does not reflecting the changed data.

const dispatch = useDispatch()
const data = useSelector((state) => state.staticPageReducer)

This is the useEffect

useEffect(() => {
        console.log(data)
        if (!data.isFetched) dispatch(fetchStaticPage(pageType))

        return () => {
          dispatch(clearStaticPage())
        }
    }, [])

This is the reducer

import { StaticPageActions } from "./actions"

const defaultState = {
    data: {},
    isFetching: false,
    isFetched: false,
    error: null,
}

const staticPageReducer = (state = defaultState, action) => {
    switch (action.type) {
        case StaticPageActions.FETCH_STATIC_PAGE_REQUEST:
            return {
                ...state,
                isFetching: true,
                isFetched: false,
            }

        case StaticPageActions.FETCH_STATIC_PAGE_SUCCESS:
            return {
                ...state,
                data: action.payload.data,
                isFetching: false,
                isFetched: true,
            }

        case StaticPageActions.FETCH_STATIC_PAGE_ERROR:
            return {
                ...state,
                isFetching: false,
                isFetched: false,
                error: action.error,
            }

        case StaticPageActions.CLEAR_STATIC_PAGE:
            return {
                ...state,
                isFetched: false,
                isFetching: false,
                data: {},
            }

        default:
            return state
    }
}

export default staticPageReducer

export const clearStaticPage = () => {
    return {
        type: StaticPageActions.CLEAR_STATIC_PAGE,
    }
}

Now the problem is when the cleanup function runs and after that console.log(data) still prints the previous value, but i was hoping that after clearStaticPage(), the data value will be cleared!

It would be great if anyone can clear my doubt here.

Upvotes: 0

Views: 1176

Answers (1)

shadow-kris
shadow-kris

Reputation: 196

The way your useEffect function is set up could be the source of the problem. When you have an empty array at the end of it, your component will only render on initialization, and the props/state inside the effect will always have their initial values (hence why your data variable is logging the same thing) - if you want it to update every time a variable changes, you can put it into that list (https://reactjs.org/docs/hooks-reference.html#useeffect).

In your case, the useEffect function would look like this:

useEffect(() => {
        console.log(data)
        if (!data.isFetched) dispatch(fetchStaticPage(pageType))

        return () => {
          dispatch(clearStaticPage())
        }
    }, [data])

Upvotes: 1

Related Questions