itsMe
itsMe

Reputation: 139

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

Upvotes: 2

Views: 931

Answers (2)

Linda Paiste
Linda Paiste

Reputation: 42188

What you are trying to do here will not work. The initial state of the reducer is just that -- the INITIAL state. It will use the value of initialState from the very first render, before your items has been updated with the fetch results. Changes to the variable initialState will not effect the reducer after it has already been created. You have to dispatch an action to store the items in your reducer.

Upvotes: 2

Paweł Czekaj
Paweł Czekaj

Reputation: 63

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.

Upvotes: 0

Related Questions