how to restore reducer state value to the initialState default value

Viewed 76

I'm trying to filter items by their category using useReducer

context.jsx

const initialState = {
    categoryName: "all item",
  };

const [state, dispatch] = useReducer(reducer, initialState);

const fetchUrl = async () => {
    const resp = await fetch(url);
    const respData = await resp.json();
    const item = respData.item;
    const category = respData.category;
    const promo = respData.promo;
    dispatch({ type: "CATEGORY_ITEM", payload: category });
  };

I want to display the category name that matched the data.

reducer.jsx

if (action.type === "FILTER_NAME") {
    if (action.payload === "all menu") {
      return { ...state, categoryName: "all menu" };
    //return { ...state, categoryName: state.categoryName};
    } else {
      return { ...state, categoryName: action.payload };
    }
  }

I cant set the categoryName back to the state value because it's been changed when I do else.

Is there a way for me to set a default value in reducer? Because if I use useState the setState won't overwrite the state default value. Thanks before

0 Answers
Related