mirror of
https://github.com/Stremio/stremio-web.git
synced 2026-04-07 02:09:40 +00:00
useSeasons refactored to use reducer to keep state consistent
This commit is contained in:
parent
05f4122480
commit
a851df5041
1 changed files with 60 additions and 12 deletions
|
|
@ -1,23 +1,71 @@
|
|||
const React = require('react');
|
||||
|
||||
const useSeasons = (metaItem) => {
|
||||
const seasons = React.useMemo(() => {
|
||||
return metaItem !== null ?
|
||||
metaItem.videos
|
||||
const seasonsReducer = (state, action) => {
|
||||
switch (action.type) {
|
||||
case 'videos-changed': {
|
||||
const seasons = action.videos
|
||||
.map(({ season }) => season)
|
||||
.filter((season, index, seasons) => {
|
||||
return season !== null &&
|
||||
!isNaN(season) &&
|
||||
typeof season === 'number' &&
|
||||
seasons.indexOf(season) === index;
|
||||
})
|
||||
:
|
||||
[];
|
||||
}, [metaItem]);
|
||||
const [season, setSeason] = React.useState(seasons[0]);
|
||||
});
|
||||
const selectedSeason = seasons.includes(state.selectedSeason) ?
|
||||
state.selectedSeason
|
||||
:
|
||||
seasons.length > 0 ?
|
||||
seasons[0]
|
||||
:
|
||||
null;
|
||||
return {
|
||||
...state,
|
||||
seasons,
|
||||
selectedSeason
|
||||
};
|
||||
}
|
||||
case 'season-changed': {
|
||||
const selectedSeason = state.seasons.includes(action.season) ?
|
||||
action.season
|
||||
:
|
||||
state.season;
|
||||
return {
|
||||
...state,
|
||||
selectedSeason
|
||||
};
|
||||
}
|
||||
default: {
|
||||
return state;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const useSeasons = (metaItem) => {
|
||||
const [{ selectedSeason, seasons }, dispatch] = React.useReducer(
|
||||
seasonsReducer,
|
||||
[metaItem],
|
||||
(metaItem) => {
|
||||
const videos = metaItem && Array.isArray(metaItem.videos) ? metaItem.videos : [];
|
||||
return seasonsReducer({}, {
|
||||
type: 'videos-changed',
|
||||
videos
|
||||
});
|
||||
}
|
||||
);
|
||||
const setSeason = React.useCallback((season) => {
|
||||
dispatch({
|
||||
type: 'season-changed',
|
||||
season
|
||||
});
|
||||
}, []);
|
||||
React.useEffect(() => {
|
||||
setSeason(seasons[0]);
|
||||
}, [seasons]);
|
||||
return [season, seasons, setSeason];
|
||||
const videos = metaItem && Array.isArray(metaItem.videos) ? metaItem.videos : [];
|
||||
dispatch({
|
||||
type: 'videos-changed',
|
||||
videos
|
||||
});
|
||||
}, [metaItem]);
|
||||
return [selectedSeason, seasons, setSeason];
|
||||
};
|
||||
|
||||
module.exports = useSeasons;
|
||||
|
|
|
|||
Loading…
Reference in a new issue