Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot read properties of null (reading 'useState') TypeError: Cannot read properties of null (reading 'useState')

I am building a react-native application. Once i initialize state i get this error feed back:

Cannot read properties of null (reading 'useState') TypeError: Cannot read properties of null (reading 'useState')

i am running react-native on the following specifications:

   "native-base": "^2.8.2",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-native": "0.71.6",
    "react-native-swiper": "^1.6.0",
    "react-native-web": "~0.18.10"

I have tried Re-installing react, both downgrades it still doesnt work. Here is my code sample. once you comment useState and the useEffect the applications works just fine.

import { StyleSheet, Text, View } from 'react-native';
import React,{ useState, useEffect } from 'react';

const data = require('../../assets/data/products.json');

const [products, setProducts] = useState([]);

useEffect(() => {
            setProducts(data);
    
            return () => {
                setProducts([])
            }
        }, [])

const productContainer = () => {
  return (
    <View>
      <Text>products </Text>
    </View>
  )
}

export default productContainer;

const styles = StyleSheet.create({})
like image 680
WiikoiTek Avatar asked Oct 27 '25 22:10

WiikoiTek


1 Answers

useState and useEffect need to be inside productContainer, not outside.

import { StyleSheet, Text, View } from 'react-native';
import React,{ useState, useEffect } from 'react';

const data = require('../../assets/data/products.json');


const productContainer = () => {
    const [products, setProducts] = useState([]);

    useEffect(() => {
        setProducts(data);
    
        return () => {
            setProducts([])
        }
    }, [])

  return (
    <View>
      <Text>products </Text>
    </View>
  )
}

export default productContainer;

const styles = StyleSheet.create({})
like image 51
eten Avatar answered Oct 30 '25 14:10

eten



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!