0
votes

Despite passing an empty array, useEffect still produces an infinite loop when I try to update the global state. I've tried not passing an empty array, adding dependencies, and even tried utilizing the useState hook inside the component itself yet nothing seems to work. There's nothing wrong with the API call, when I remove the function to update the state there is no loop. When i do this anywhere else in my code things work fine. Here is the functional component useEffect is being called in.

const Posts = () => {
    const [{auth}] = useAuth();
    const [{profile},, setPosts] = useProfile();
    const {getPostsByUser} = PostApi()
    useEffect(() => {
        const fetch = async () => {
            const response = await getPostsByUser(auth.user._id, auth.token)
            setPosts(response)
        }
        fetch()
    }, [])
    console.log(profile)
    return(
        <div className="User-Post">
            <div className="New-Post">
                <NewPost />
            </div>
            <div className="User-Posts-Content">
                {
                    profile.posts ? profile.posts.map((item, key) => {
                        return <Post post={item} />
                    }) : null
                }
            </div>
        </div>
    )
}

Here is the useProfile hook:

const useProfile = () => {
    const [{...profile}, setState] = useStore()

    const setPosts = posts => {
        setState(state => ({
            ...state,
            profile: {
                ...state.profile,
                posts: posts
            }
        }))
    }

    return [profile, setPosts]
}

heres the global store:

function makeStore() {
    // Make a context for the store
    const Context = React.createContext();

    // Make a provider that takes an initialValue
    const Provider = ({ initialValue, children }) => {
      // Make a new state instance (could even use immer here!)
      const [state, setState] = useState(initialValue);
      // Memoize the context value to update when the state does
      const contextValue = useMemo(() => [state, setState], [state]);

      // Provide the store to children
      return <Context.Provider value={contextValue}>{children}</Context.Provider>;
    };

    // A hook to help consume the store
    const useStore = () => useContext(Context);

    return { Provider, useStore };
}
1
What's the output from the console? Also, what made you realize it was an infinite loop?Khauri
The output on the console is the api repeatedly being called and the state repeatedly being updatededAnthony Gayflor

1 Answers

0
votes

this may help

  const [toggle, setToggle] = useState(false);
   useEffect(() => {
        const fetch = async () => {
            const response = await getPostsByUser(auth.user._id, auth.token)
            setPosts(response)
        }
        fetch()
    }, toggle)

user this structure whenever required