0

I'm calling an api that returns a bunch of objects and then dispatching the response.

When i looked on to redux devtool, the object is correctly dispatched, but in state it stores as "undefined[object Object],[object Object],[object Object],........,".

API format:

0: {id: 188, category_id: 23, en_name: "The Local", en_description: "Lorem Ipsum", price: 12, …}
1: {id: 212, category_id: 25, en_name: "Protein", en_description: "Lorem Ipsum", price: 5, …}
2: {id: 205, category_id: 24, en_name: "House Buttermilk Biscuits and Gravy", en_description: "Lorem Ipsum", price: 10, …}
3: {id: 206, category_id: 24, en_name: "Griddle me this Pancakes", en_description: "Lorem Ipsum", price: 10, …}

Redux devtool shown dispatch is also same as the above api.

while checking the state with redux devtool,

"undefined[object Object],[object Object],[object Object],........,"

Code :

  useEffect(() => {
    async function fetchData() {
      const response = await axios.get(
        "https://theapi.com/something/something"
      );
      let { categories, menus } = response.data;

      setCategories(categories);
      dispatch(setItemToCart(menus));
    }
    fetchData();
  }, []);

Reducers and action :

const initialState = {
  items: [],
};

export const addItems = createSlice({
  name: "cart",
  initialState,
  reducers: {
    setItemToCart(state, action) {
      state.items = state.item + action.payload;
    },
  },
});

export const { setItemToCart } = addItems.actions;
0

1 Answer 1

1

The reducer should be implemented as

state.items = [...state.items, action.payload];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.