Hello everyone! I’ve been struggling with this one for a few days now.
Down bellow Im posting my subreddits component and subredditsSlice. Im using an async thunk to fetch the subreddits from the reddit API which gets dispatched in the subreddits component with useEffect.
In the subredditsSlice, using extrareducers, if the request to the API is fulfilled, the state.subreddits should be update the state with the payload, but its not.
Im checking it using the redux dev tools and the request is coming back fulfilled and i have logged the response to the console, but i just have no idea why the state.subreddits array is still empty.
please help
subredditsSlice
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
export const fetchSubreddits = createAsyncThunk('subreddits/getSubreddits',
async() => {
const response = await fetch('https://www.reddit.com/subreddits.json');
const json = await response.json();
return json.data.children.map(subreddit => subreddit.data)
});
const subredditsSlice = createSlice({
name: 'subreddits',
initialState: {
subreddits:[],
isLoading: false,
hasError: false
},
reducers: {},
extrareducers:{
[fetchSubreddits.pending]:(state, action)=>{
state.isLoading = true;
state.hasError = false;
},
[fetchSubreddits.fulfilled]:(state, action)=>{
state.isLoading = false;
state.hasError = false;
state.subreddits = action.payload;
},
[fetchSubreddits.rejected]: (state, action)=>{
state.isLoading = false;
state.hasError = true
}
}
});
export default subredditsSlice.reducer;
subreddits component
import React, { useEffect, useState } from "react";
import {useSelector, useDispatch} from 'react-redux';
import { setCurrentSubreddit } from '../Reddit/RedditSlice';
import { fetchSubreddits, selectSubreddits } from "./SubRedditsSlice";
const SubReddits = () =>{
const subreddits = useSelector(state => state.subreddits.subreddits);
const isLoading = useSelector(state => state.subreddits.isLoading);
const error = useSelector(state => state.subreddits.error);
const dispatch = useDispatch();
useEffect(()=>{
dispatch(fetchSubreddits())
}, [dispatch])
console.log(subreddits);
return(
<div>
<h2>Subreddits</h2>
<ul className="subreddits-list">
{subreddits.map((subreddit) => (
<li
key={subreddit.id}
>
<button
type="button"
>
<img
src={
subreddit.icon_img ||
`https://api.adorable.io/avatars/25/${subreddit.display_name}`
}
alt={`${subreddit.display_name}`}
/>
{subreddit.display_name}
</button>
</li>
))}
</ul>
</div>
)
}
export default SubReddits;