0

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();
Linda Paiste
  • 38,446
  • 6
  • 64
  • 102

1 Answers1

1

Maybe instead of useImmer you should use useImmerReducer in AppProvider, see below:

Immer powered reducer, based on useReducer hook

Reading the documentation I found the following:

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

So your example would be:

const [state, dispatch] = useImmerReducer({ ...defaultState });

In more details:

See from the documentation of useImmer which is similar to useState:

useImmer(initialState) is very similar to useState. The function returns a tuple, the first value of the tuple is the current state, the second is the updater function, which accepts an immer producer function, in which the draft can be mutated freely, until the producer ends and the changes will be made immutable and become the next state.

So technically what you are looking for is the reducer one (useImmerReducer).

Dharman
  • 30,962
  • 25
  • 85
  • 135
norbitrial
  • 14,716
  • 7
  • 32
  • 59