Reputation: 186
I am making an audio player.
This is my audio
tag:
<audio
ref={audioReference}
src={currentSong.audio}
onTimeUpdate={timeUpdateHandler}>
</audio>
and here is the timeUpdateHandler
:
const timeUpdateHandler = (e) => {
const current = e.target.currentTime;
const duration = e.target.duration;
};
Here, current
contains the current time as the song plays and duration
contains the duration of the song that is playing.
I want to push these two variables to the redux state so that I can show them on the screen.
This is my redux state in another file:
const initState = {
allSongs: songData(),
currentSong: { ...songData()[0] },
isPlaying: false,
isLibraryOpen: false,
currentTime: 0,
duration: 0,
};
This is the action type and action creator:
const PLAYER_TIMER_UPDATE = "timerUpdate";
export const timerUpdate = () => {
return {
type: PLAYER_TIMER_UPDATE,
};
};
How should the action type and the reducer function look like and how will the payload work here? I am new to this so it is very confusing.
Upvotes: 0
Views: 146
Reputation: 891
Your action could contains that time information
const PLAYER_TIMER_UPDATE = "timerUpdate";
export const timerUpdate = (current, duration) => {
return {
type: PLAYER_TIMER_UPDATE,
payload: {time: current, duration }
};
};
Then you can have as many reducers you want to calculate the state. Let say isPlaying
reducer will return true when action is PLAYER_TIMER_UPDATE. Similar currentTime and duration can be 2 different reducers.
Here is one approach, you might need to check combineReducers
reducers.js
const isPlaying = (state=false, action) => {
if(action.type=== PLAYER_TIMER_UPDATE) return true;
// implement the stop
return state
},
const currentTime = (state=0, action) =>{
if(action.type=== PLAYER_TIMER_UPDATE) return action.payload.time;
return state
}
const duration = (state=0, action) =>{
if(action.type=== PLAYER_TIMER_UPDATE) return action.payload.duration;
return state
}
export default combineReducers({
isPlaying,
currentTime,
duration,
})
Upvotes: 1