0

I have a question. So, I'm new to react and now I'm working in a project. I use redux-toolkit to handle my states and I'm also using createEntityAdapter to set Initial state, and the question is this: how can I handle error when using createEntityAdapter when error happens. or do I have to create global error state to handle errors from asyncThunk? is it good to use a global error state?

here is my code:

import { createSlice, createAsyncThunk ,createEntityAdapter } from '@reduxjs/toolkit'

export const searchRecipe = createAsyncThunk('recipes/SearchRecipe', async (title, { rejectWithValue }) => {
  try {
    const response = await axios.get(`/recipes?title=${title}`)
    return response?.data?.data
  } catch(err) {
    return rejectWithValue(err?.response?.data?.message || 'Something went wrong')
  }
})

const recipeAdapter = createEntityAdapter({
  selectId: (recipe) => recipe.recipe_id
})

const recipeSlice = createSlice({
  name: 'recipes',
  initialState: recipeAdapter.getInitialState(),
  extraReducers: {
    [getRecipes.fulfilled]: (state, action) => {
      recipeAdapter.setAll(state, action.payload)
    }
  }
})

export const recipeSelectors = recipeAdapter.getSelectors((state) => state.recipes)
export default recipeSlice.reducer

Last but not least. is it any better solution to use redux-toolkit (resource i can read or watch) Thanks

1 Answers1

0

Something like this:

 import { createSlice, PayloadAction, createEntityAdapter } from "@reduxjs/toolkit";
import { PointType } from "../Types/PointType";
import { ErrorType } from "../Types/ErrorType";

type InitialStateType = {
  data: PointType;
  error: ErrorType;
};

export const pointsAdapter = createEntityAdapter<InitialStateType>({
  selectId: point => point.data.Id,
  sortComparer: (a, b) => a.data.Subject.localeCompare(b.data.Subject),
});

const initialState = pointsAdapter.getInitialState({
  data: [],
  error: { message: "" },
});

const pointSlice = createSlice({
  name: "pointsSlice",
  initialState,
  reducers: {
    fetchPointsSuccess: (state, action) => {
      pointsAdapter.setAll(state, action.payload);
    },
    fetchSinglePointSuccsess: (state, action) => {
      pointsAdapter.updateOne(state, action.payload);
    },
    fetchPointsFailure: state => {
      state.error.message = "Can not fetch points";
    },
    updatePointsFailure: state => {
      state.error.message = "Can not update point";
    },
  },
});

export const { fetchPointsSuccess, fetchPointsFailure, updatePointsFailure, fetchSinglePointSuccsess } =
  pointSlice.actions;
export const pointReducer = pointSlice.reducer;