Home > Software design >  context is giving me undefined
context is giving me undefined

Time:09-23

I am uncertain why after the initial load the values in context becomes undefined.

The way I have my context written up is:

export const ProductListContext = createContext({});

export const useListProductContext = () => useContext(ProductListContext);

export const ListProductContextProvider = ({ children }) => {
  const [listProduct, setListProduct] = useState({
    images: [],
    title: "Hello",
  });
  return (
    <ProductListContext.Provider value={{ listProduct, setListProduct }}>
      {children}
    </ProductListContext.Provider>
  );
}; 

On the initial load of my component. I so get the listProduct to be correct as a console.log will produce

the list is Object {
  "images": Array [],
  "title": "Hello",
}

The problem is when I try to read listProduct again after it says it is undefined unless I save it to a useState. Any help on this is appreciated. The problem is within the pickImage function

// Initial has all properties correctly
const { listProduct, setListProduct } = useListProductContext();
// Seems to work at all times when I save it here
const [product] = useState(listProduct);
console.log('the list product listed is ', listProduct);
useEffect(() => {
  (async () => {
    if (Platform.OS !== 'web') {
      const {
        status,
      } = await ImagePicker.requestMediaLibraryPermissionsAsync();
      if (status !== 'granted') {
        alert('Sorry, we need camera roll permissions to make this work!');
      }
    }
  })();
}, []);

const pickImage = async () => {
  let result = await ImagePicker.launchImageLibraryAsync({
    mediaTypes: ImagePicker.MediaTypeOptions.Images,
    allowsEditing: true,
    aspect: [4, 3],
    quality: 1,
    exif: true,
  });
  // PROBLEM - listProduct is undefined
  console.log('before copy it is ', listProduct);
  const listProduct = { ...product };
  console.log('the list is', listProduct);
  listProduct.images.push(result.uri);
  // listProduct.images.push(result.uri);
  // const images = listProduct.images;
  // images.push(result.uri);
  setListProduct({ ...listProduct });
  return;
};

CodePudding user response:

Your useListProductContext is violating the rules of hooks, as React sees the use qualifier to validate the rules of hooks.

Rules of Hooks

Using a Custom Hook

"Do I have to name my custom Hooks starting with “use”? Please do. This convention is very important. Without it, we wouldn’t be able to automatically check for violations of rules of Hooks because we couldn’t tell if a certain function contains calls to Hooks inside of it."

  • Related