I am trying to implement useContext()
in my React app in order to maintain a state in different pages. Upon debugging my script, I realized even adding my useContext()
component to one of my pages causes all of the fetch
functions in the page to break.
This is the page with the fetch calls:
import React, { useState, useEffect } from 'react';
import { useCreate } from '../scripts/CreateContext';
export default function Create() {
// other states
const { petList, fetched, update, fetch } = useCreate(); // this line breaks the fetch calls
const fetchData = async () => {
try {
const user = await checkLogin(); // function not shown
if (user) {
await listPets(user.$id);
}
} catch (error) {
console.log(error);
} finally {
setLoading(false);
}
}
async function listPets(userId) {
try {
const res = await fetch("/api/pets/" + userId);
const data = await res.json();
setPets(data.pets);
} catch (error) {
console.log(error);
}
}
useEffect(() => {
fetchData();
}, []);
return (
<>
// content here
</>
);
}
And this is the page with the useContext
component:
import React, { createContext, useContext, useState } from 'react';
export const CreateContext = createContext({});
export const CreateProvider = ({ children }) => {
const [pets, setPets] = useState([]);
const [fetched, setFetched] = useState(false);
const update = (newPets) => {
setPets(newPets);
};
const fetch = () => {
setFetched(true);
};
return (
<CreateContext.Provider value={{ pets, fetched, update, fetch }}>
{children}
</CreateContext.Provider>
);
};
export const useCreate = () => {
return useContext(CreateContext);
};
My app is wrapped with the Context Provider as well. I’m sure the issue is the useContext()
because the second I remove it from the page, the fetch calls work again.
The only error I get is a cannot read properties of undefined error
when res.json() is called.
Thanks in advance for any help!