Is there a way to set fetched data to Redux state inside of reducer file itself? I want my 'videoList' and 'showVideos' to be equal to fetched data on first render.
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import axios from 'axios'
const VIDEOS_API = 'http://localhost:3001/api'
export const fetchVideos = createAsyncThunk('videos/fetchVideos', async () => {
try {
const response = await axios.get(VIDEOS_API)
return response.data;
} catch (error) {
return error.message
}
})
const initialString = '';
export const videosSlice = createSlice({
name: 'videos',
initialState: {
videoList: [],
showVideos: [],
status: 'idle',
videoCategories: categories,
watchLaterList: [],
searchVideo: initialString,
}
})
I've only tried to set it through component, where data is being rendered. I added this reducer:
reducers: {
setInitialVideos: (state, action) => {
state.showVideos = action.payload;
state.videoList = action.payload;
}
}
And used it like this:
useEffect(() => {
if(status === 'idle') {
const response = dispatch(fetchVideos())
dispatch(setInitialVideos(response))
}
}, [status])
And got an error: 'A non-serializable value was detected in the state'.
The data I am fetching is array of objects equivalent to this:
[
{
"title": "Punic wars",
"thumbnail": "https://www.mindrevolt.org/images/posts/what-if-carthage-won-the-punic-wars-the-world-we-know-today-would-be-totally-different.jpg",
"description": "The Punic Wars was a series of wars between 264 and 146 BC that were fought between Rome and Carthage....",
"category": ["rome"],
"likes": 451,
"id": 1,
"slug": "punic-wars",
"date": "10-22-2022",
"source": "url",
"comments": []
},
{...}
]
What would be a correct way to set fetched data to slice's state?