Home > Software design >  How to handle an null object from the database in React use state
How to handle an null object from the database in React use state

Time:11-01

I have a chicken and egg problem. I have a JSON object in my database which I use in my state like:

const [formFields, setFormFields] = useState(myObject);

Were myObject is a JSON Object that's coming from my database.

Problem

The issue I have is that for me to have the object in my database, I have to add it from the client, which I can't do because I get the error:

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

Because yes it's true, there isn't an object yet. So I can't update my database from my form on the page since the page won't load because the is no JSON in the DB. (What comes first, chicken and egg situation)

I tried to use useEffect to create set a value in myObject trying to seed the DB so that it wont be empty:

useEffect(() => {
        setMyObject([{name: 'Alice',salary: 100,}]);
    }, []); 

But this isn't working.

I tried to set the state conditionally like this.

if (myObject === null) {
       const [formFields, setFormFields] = useState(myObject);
    } else {
        const [formFields, setFormFields] = useState([{name: 'Alice',salary: '100'}]);
    }

But this isn't allowed.

How do I approach this problem?

Requested code

When I get my Object from DB, i save it to the state myObject. I update the DB with this.

updateData = async () => {
        try {
            await fetch(`/api/posts/${id}`, {
                method: 'PUT',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({
                    Object: myObject,
            })
        })
        refreshData()
    } catch (error) {
        toast.error('Document could not be updated')
        console.error(error);
    }
};

CodePudding user response:

You're getting

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

because you're trying to map over a null. What you can do to avoid this is to initialize your formFields state as an array, like so:

const [formFields, setFormFields] = useState([]);
  • Related