Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access current redux state from useEffect?

I have a list of objects ("Albums" in my case) fetched from the database. I need to edit these objects. In the editing component in the useEffect hook I fire up the action for getting the needed album using it's ID. This action works. However in the same useEffect I am trying to fetch the changed by before fired action redux state. And now I face the problem - all I am fetching is the previos state. How can I implement in the useEffect fetching of current redux state?

I've seen similar questions here, however none of the answers were helpfull for my use case.

I am using redux-thunk.

Editing component. The problem appears in setFormData - it's fetching previous state from the reducer, not the current one. It seems that it fires before the state gets changed by the getAlbumById:

//imports

const EditAlbum = ({
  album: { album, loading},
  createAlbum,
  getAlbumById,
  history,
  match
}) => {
  const [formData, setFormData] = useState({
    albumID: null,
    albumName: ''
  });

  useEffect(() => {
    getAlbumById(match.params.id);

    setFormData({
      albumID: loading || !album.albumID ? '' : album.albumID,
      albumName: loading || !album.albumName ? '' : album.albumName
    });

  }, [getAlbumById, loading]);

const { albumName, albumID } = formData;

  const onChange = e =>
    setFormData({ ...formData, [e.target.name]: e.target.value });

  const onSubmit = e => {
    e.preventDefault();
    createAlbum(formData, history, true);
  };

  return ( //code );
};



EditAlbum.propTypes = {
  createAlbum: PropTypes.func.isRequired,
  getAlbumById: PropTypes.func.isRequired,
  album: PropTypes.object.isRequired
};

const mapStateToProps = state => ({
  album: state.album
});

export default connect(
  mapStateToProps,
  { createAlbum, getAlbumById }
)(withRouter(EditAlbum));

Action:

export const getAlbumById = albumID => async dispatch => {
  try {
    const res = await axios.get(`/api/album/${albumID}`);

    dispatch({
      type: GET_ALBUM,
      payload: res.data
    });
  } catch (err) {
    dispatch({
      type: ALBUMS_ERROR,
      payload: { msg: err.response.statusText, status: err.response.status }
    });
  }
};

reducer

const initialState = {
  album: null,
  albums: [],
  loading: true,
  error: {}
};

const album = (state = initialState, action) => {
  const { type, payload } = action;
  switch (type) {
    case GET_ALBUM:
      return {
        ...state,
        album: payload,
        loading: false
      };
    case ALBUMS_ERROR:
      return {
        ...state,
        error: payload,
        loading: false
      };
    default:
      return state;
  }
};

Will be grateful for any help/ideas

like image 978
ysvet Avatar asked Sep 26 '19 08:09

ysvet


1 Answers

You should split up your effects in 2, one to load album when album id changes from route:

const [formData, setFormData] = useState({
    albumID: match.params.id,
    albumName: '',
});
const { albumName, albumID } = formData;

// Only get album by id when id changed
useEffect(() => {
    getAlbumById(albumID);
}, [albumID, getAlbumById]);

And one when data has arrived to set the formData state:

// Custom hook to check if component is mounted
// This needs to be imported in your component
// https://github.com/jmlweb/isMounted

const useIsMounted = () => {
  const isMounted = useRef(false);
  useEffect(() => {
    isMounted.current = true;
    return () => (isMounted.current = false);
  }, []);
  return isMounted;
};

// In your component check if it's mounted 
// ...because you cannot set state on unmounted component
const isMounted = useIsMounted();
useEffect(() => {
  // Only if loading is false and still mounted
  if (loading === false && isMounted.current) {
    const { albumID, albumName } = album;
    setFormData({
      albumID,
      albumName,
    });
  }
}, [album, isMounted, loading]);

Your action should set loading to true when it starts getting an album:

export const getAlbumById = albumID => async dispatch => {
  try {
    // Here you should dispatch an action that would
    //  set loading to true
    // dispatch({type:'LOAD_ALBUM'})
    const res = await axios.get(`/api/album/${albumID}`);

    dispatch({
      type: GET_ALBUM,
      payload: res.data
    });
  } catch (err) {
    dispatch({
      type: ALBUMS_ERROR,
      payload: { msg: err.response.statusText, status: err.response.status }
    });
  }
};

Update detecting why useEffect is called when it should not:

Could you update the question with the output of this?

//only get album by id when id changed
useEffect(() => {
  console.log('In the get data effect');
  getAlbumById(albumID);
  return () => {
    console.log('Clean up get data effect');
    if (albumID !== pref.current.albumID) {
      console.log(
        'XXXX album ID changed:',
        pref.current.albumID,
        albumID
      );
    }
    if (getAlbumById !== pref.current.getAlbumById) {
      console.log(
        'XXX getAlbumById changed',
        pref.current.getAlbumById,
        getAlbumById
      );
    }
  };
}, [albumID, getAlbumById]);
like image 58
HMR Avatar answered Nov 01 '22 21:11

HMR