首页 > 解决方案 > how to pass useState state value to useReducer initialstate

问题描述

I want to pass a value from useState state value to useReducer initialstate.

const [item, setItem] = useState([]);

const initialState = {
    menuOpen: true,
    promoOpen: false,
    couponOpen: false,
    cartOpen: false,
    orderOpen: false,
    orderAmount: 1,
    filteredItem: 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;
    setItem(item);
    setCategory(category);
    setPromo(promo);
    setFilterItem(item);
  };

But when I do console.log(state.filteredItem), I got an empty array so I assume that it didn't pass the value to the initialState. Is there a way for me to pass a useState state value to useReducer initialState value? Thanks before

标签: reactjsreact-hooks

解决方案


const [item, setItem] = useState([]);

You declared your state with an empty array therefore that's what filteredItem shows. If you've set your state later on, in order to change it in the reducer I think you need to use dispatch function.


推荐阅读