Код: Выделить всё
export const Dashboard: React.FC = () => {
const dispatch: AppDispatch = useDispatch();
const { service, loading, error } = useSelector((state: RootState) => state.services);
useEffect(() => {
dispatch(fetchAService());
}, [dispatch]);
useEffect(() => {
console.log('Services after fetch:', service);
}, [service]);
if (error) {
return
Error: {error}
;
}
return (
{loading ? (
) : (
)}
Our Service
{loading ? (
) : (
Array.isArray(service) && service.length > 0 ? (
service.map((myservice) => (
))
) : (
No services available
)
)}
);
}
Код: Выделить всё
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';
export const fetchServices = createAsyncThunk('services/fetchServices', async () => {
const response = await axios.get('htttp:localhost:5000/services');
return response.data;
});
interface Service {
id: string;
title: string;
imageUrl: string;
link: string;
}
interface ServicesState {
services: Service[];
loading: boolean;
error: string | null;
}
const initialState: ServicesState = {
services: [],
loading: false,
error: null,
};
const servicesSlice = createSlice({
name: 'services',
initialState,
reducers: {},
extraReducers: (builder) => {
builder
.addCase(fetchServices.pending, (state) => {
state.loading = true;
state.error = null;
})
.addCase(fetchServices.fulfilled, (state, action) => {
state.loading = false;
state.services = action.payload;
})
.addCase(fetchServices.rejected, (state, action) => {
state.loading = false;
state.error = action.error.message || 'Failed to fetch services';
});
},
});
export default servicesSlice.reducer;
Подробнее здесь: https://stackoverflow.com/questions/793 ... e-but-i-ca