0

I am using Redux Toolkit's createAsyncThunk and Axios for async requests. At first, it works, but when I was doing sth with scss, the chrome gives me that TypeError: Cannot read properties of undefined (reading 'map'). I didn't change anything about redux and thunk but useSelector gets nothing. Also, the interface(it works) didn't give any response.

thunk and slice:

export const getTopBanners = createAsyncThunk(
    'home/getTopBanners',
    async ()=>{
        console.log('hello?');
        const response = await axiosGetTopBanner();
        console.log('res:'+response);
        return response.banners
    }
)

export const topBannerSlice = createSlice({
    name:'topBanner',
    initialState:{
        pics:[],
        isLoading:false
    },
    extraReducers:{
        [getTopBanners.pending]:(state)=>{
            state.isLoading = true;
        },
        [getTopBanners.fulfilled]:(state,action)=>{
            state.pics = action.payload;
            state.isLoading = false;
        },
        [getTopBanners.rejected]:(state)=>{
            state.isLoading = false;
        }
    }
})

component:

const dispatch = useDispatch();
//gets nothing here
const topBanners = useSelector((state) => state.topBanner.pics);
useEffect(() => {
    dispatch(getTopBanners());
  }, [dispatch]);

store:

const store = configureStore({
  reducer:{
    topBanner:topBannerReducer,
    recommendData:recommendDataReducer
  }
})
  • I think axios returns the data of the response at `data`. Try: `return response.data.banners` or just `return response.data` – Rashomon Jun 22 '22 at 08:29
  • hi bro, thanks for ur help but it still doesn't work. I have tested the interface in another JS file. It gives me [OK]xxx/xxx in PowerShell. But PowerShell shows nothing here with `await axiosGetTopBanner();`. So, I'm wondering if maybe this function doesn't fetch anything? – ASElieen Jun 22 '22 at 09:19
  • 1
    Maybe you can show your `axiosGetTopBanner` function – Rashomon Jun 22 '22 at 09:20
  • `export const axiosGetTopBanner = () => { return instance.get("/banner"); };` and I tried to use this function in app.js directly, It works. – ASElieen Jun 22 '22 at 10:00
  • Since you're logging the response, is it what you're expecting it to be? – timotgl Jun 22 '22 at 11:07

1 Answers1

0

extraReducers: (builder) => {
    builder
      .addCase(getTopBanners.fulfilled, (state, action) => {
            state.pics = action.payload; 
      });
}
grit
  • 83
  • 4