I'm trying to share data between component using ContextAPI in ReactJs. But I have a stuck when using it. This err is :
"TypeError: Object is not iterable (cannot read property Symbol(Symbol.iterator))"
at
line 7: *const [state, dispatch] = useContext(AppContext);*
This is my code.
file context.js
import React from "react";
import { useImmer } from "use-immer";
const defaultState = {
feed: [],
listFeed: [],
};
const AppContext = React.createContext();
const AppProvider = ({ children }) => {
const [state, dispatch] = useImmer({ ...defaultState });
return (
<AppContext.Provider value={[state, dispatch]}>
{children}
</AppContext.Provider>
);
};
export { AppProvider, AppContext };
and file useContextApp.js
import { useContext} from "react";
import { AppContext } from "./context";
const useAppContext = () => {
const [state, dispatch] = useContext(AppContext);
function updateFeed(feed) {
dispatch((draft) => {
draft.feed = feed;
})
}
function updateListFeed(listFeed) {
dispatch((draft) => {
draft.listFeed = listFeed;
})
}
return {
...state,
updateFeed,
updateListFeed,
};
};
export { useAppContext };
and using it in HomePage.
const { updateFeed} = useAppContext();