Вопрос пользователя:
export type TIngredient = {
_id: string;
name: string;
type: string;
proteins: number;
fat: number;
carbohydrates: number;
calories: number;
price: number;
image: string;
image_large: string;
image_mobile: string;
};
import {
createSlice,
createAsyncThunk,
PayloadAction,
createSelector
} from '@reduxjs/toolkit';
import { TIngredient } from '../../utils/types';
import { getIngredientsApi } from '../../utils/burger-api';
type TIngredientState = {
ingredients: Array<TIngredient>;
loading: boolean;
error?: string | null;
};
const initialState: TIngredientState = {
ingredients: [],
loading: false,
error: ''
};
export const fetchIngredients = createAsyncThunk<TIngredient[]>(
'ingredients/getAll',
getIngredientsApi
);
const ingredientSlice = createSlice({
name: 'ingredients',
initialState,
reducers: {},
extraReducers: (builder) => {
builder
.addCase(fetchIngredients.pending, (state) => {
state.loading = true;
state.error = null;
})
.addCase(fetchIngredients.rejected, (state, action) => {
state.loading = false;
state.error = action.error.message;
})
.addCase(
fetchIngredients.fulfilled,
(state, action: PayloadAction<TIngredient[]>) => {
state.loading = false;
state.ingredients = action.payload;
}
);
},
selectors: {
getIngredientsSelector: (state) => state.ingredients,
getLoadingSelector: (state) => state.loading,
getErrorSelector: (state) => state.error
}
});
export const ingredientSliceReducer = ingredientSlice.reducer;
export const { getIngredientsSelector, getLoadingSelector, getErrorSelector } =
ingredientSlice.selectors;
export default ingredientSlice;
import { configureStore, combineReducers } from '@reduxjs/toolkit';
import { burgerSliceReducer } from './slices/burgerSlice';
import { ingredientSliceReducer } from './slices/ingredientSlice';
import {
TypedUseSelectorHook,
useDispatch as dispatchHook,
useSelector as selectorHook
} from 'react-redux';
const rootReducer = combineReducers({
ingredients: ingredientSliceReducer,
burgers: burgerSliceReducer
}); // Заменить на импорт настоящего редьюсера
const store = configureStore({
reducer: rootReducer,
// middleware: (getDefaultMiddleware) => getDefaultMiddleware({
// serializableCheck: false,
// immutableCheck: false,
// thunk: true
// }),
devTools: process.env.NODE_ENV !== 'production'
});
export type RootState = ReturnType<typeof rootReducer>;
export type AppDispatch = typeof store.dispatch;
export const useDispatch: () => AppDispatch = () => dispatchHook();
export const useSelector: TypedUseSelectorHook<RootState> = selectorHook;
export default store;
необходимо взять данные из store , использовать useSelectors, использовтаь id элемента и дописать компонент отображения деталей конкретного ингредиента :
import { FC } from 'react';
import { Preloader } from '../ui/preloader';
import { IngredientDetailsUI } from '../ui/ingredient-details';
import { getIngredientsSelector } from '../../services/slices/ingredientSlice';
import { useSelector } from 'react-redux';
import { useLocation } from 'react-router-dom';
import { TIngredient } from '@utils-types';
export const IngredientDetails: FC = () => {
/** TODO: взять переменную из стора */
const ingredientData = ...;
if (!ingredientData) {
return <Preloader />;
}
return <IngredientDetailsUI ingredientData={ingredientData} />;
};
Ответ нейросети:
Пройдите быструю авторизацию для просмотра: Войти через Google
Войти через Яндекс
Войти через VK
import React, { FC } from 'react';
import { Preloader } from '../ui/preloader';
import { IngredientDetailsUI } from '../ui/ingredient-details';
import { getIngredientsSelector } from '../../services/slices/ingredientSlice';
import { useSelector } from 'react-redux';
import { useLocation } from 'react-router-dom';
import { TIngredient } from '@utils-types';
export const IngredientDetails: FC = () => {
const location = useLocation();
const ingredients = useSelector(getIngredientsSelector);
const ingredientId = location.pathname.split('/').pop();
const ingredientData = ingredients.find((ingredient: TIngredient) => ingredient._id === ingredientId);
if (!ingredientData) {
return <Preloader />;
}
return <IngredientDetailsUI ingredientData={ingredientData} />;
};