Can someone please help me to find what exact problem is with below code, as i am new in redux.
product-slice.js
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";<br/>
import axios from "axios";<br/>
const initialState = {<br/>
products: [],<br/>
sample: "Hello World",<br/>
};<br/>
<br/>
const productSlice = createSlice({<br/>
name: "productSlice",<br/>
initialState,<br/>
reducers: {<br/>
getProducts(state, action) {<br/>
const p = action.payload;<br/>
console.log(p);<br/>
},<br/>
},<br/>
extraReducers: (builder) => {<br/>
builder.addCase(fetchProductData.fulfilled, (state, action) => {<br/>
state.products.push(action.payload);<br/>
});<br/>
},<br/>
});<br/>
export const fetchProductData = createAsyncThunk(<br/>
"products/fetchProducts",<br/>
async (_, thunkAPI) => {<br/>
try {<br/>
const response = await axios.get("http://localhost:8080/products");<br/>
return await response.data;<br/>
} catch (error) {<br/>
return error;<br/>
}<br/>
}<br/>
);<br/>
export const productActions = productSlice.actions;<br/>
export default productSlice;<br/>
ProductList.js(Component)<br/>
const ProductList = (props) => {<br/>
const history = useHistory();<br/>
const hello = useSelector((state) => state.products.sample);<br/>
const dispatch = useDispatch();<br/>
<br/>
useEffect(() => {<br/>
dispatch(fetchProductData);<br/>
}, [dispatch]);<br/>
You should call an action as a function inside dispatch() like dispatch(fetchProductData()) and implement redux/toolkit with thunk middleware like below (example):
as you can see in reduxToolkitCreateAsyncThunk
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import { userAPI } from './userAPI'
// First, create the thunk
const fetchUserById = createAsyncThunk(
'users/fetchByIdStatus',
async (userId, thunkAPI) => {
const response = await userAPI.fetchById(userId)
return response.data
}
)
// Then, handle actions in your reducers:
const usersSlice = createSlice({
name: 'users',
initialState: { entities: [], loading: 'idle' },
reducers: {
// standard reducer logic, with auto-generated action types per reducer
},
extraReducers: (builder) => {
// Add reducers for additional action types here, and handle loading state as needed
builder.addCase(fetchUserById.fulfilled, (state, action) => {
// Add user to the state array
state.entities.push(action.payload)
})
},
})
// Later, dispatch the thunk as needed in the app
dispatch(fetchUserById(123))