in the reducer function, I want to initialize the initialState which is first updated by some data through an API call (by Axios) then it will pass through the reducer function.
The problem is when it is being updated by through an API call, the reducer has not taken the updated state, which I came to realize when I access the initialState in a different component, that will show me the very first initialization.
Initial State
var seriesData = {
horror:[],
comedi:[],
romantic:[]
}
API call through AXIOS and try to update the initial state
var gen_typ = ['horror','comedi','romantic']
gen_typ.forEach(elm => {
axios.get(`${process.env.REACT_APP_SD_API}${elm}`)
.then((result) => {
seriesData = {...seriesData,elm:result}
}).catch((err) => {
console.log(err);
});
});
Reducer function
export function SD_Operation(state = seriesData,action){
switch(action.type){
case "GET_MORE":
return{
...state,
[action.payload.genTyp]:[...state[action.payload.genTyp],action.payload.data]}
default:
return state;
}
}
when I access the initial state in one of my components and console out
inside component
var Series_data = useSelector(state => state.SD_Operation);
useEffect(()=>{
console.log('@login page',Series_data) ;
},[])
output I get
@login page {horror: Array(0), comedi: Array(0), romantic: Array(0)}
comedi: []
horror: []
romantic: []
output I expect
an array of data
{horror: Array(some length), comedi: Array(some length), romantic: Array(some length)}
comedi: [{},{}....]
horror: [{},{}....]
romantic: [{},{}....]
This is a typical scenario, and commonly solved differently:
componentDidMount or via a useEffect with empty dep. array).