How can I watch for changes from reducer in react component?

Viewed 569

I have react app, and I am using redux as a store. Along with redux i am using redux-thunk. For example, i have action getUsers that fetch all users and storing them in user reducer. Also, if there is some error while fetching them i store that error. My question is how to in react component named UsersOverwiew watch for changes happend in reducer, for example error, and show that error to user? I did it with useEffect hook, but is there better way?

User reducer

case GET_USERS_BEGIN:
        return {
            ...state,
            users: {
                loading: true,
                error: {},
                data: []
            }
        };
    case GET_USERS_SUCCESS:
        return {
            ...state,
            users: {
                loading: false,
                error: {},
                data: action.users
            }
        };
    case GET_USERS_FAILURE:
        return {
            ...state,
            users: {
                ...state.users,
                loading: false,
                error: action.error,
            }
        };

UserOverview component

// fetching users

useEffect(() =>{

    getUsers();

}, []);

// watch for changes in user reducer

useEffect(() =>{

    if(users.error){
        // if error happend do something
    }

}, [users]);

This is only small part of code, i have already everything connected, component and reducer, but i wanted to simplify it as much as i can.

1 Answers

You are doing it the correct way if you are using functional components. The above answer which suggests componentWillMount() requires class based components.

However doing it with useEffect is completely fine.

Related