TypeError: Cannot read property 'categories' of null

Viewed 2906

My back-end terminal returns null and TypeError: Cannot read property 'categories' of null, what do I lack on my code? It also returns null on my console.log(user) on my controllers

This is my function:

function addCategory(e) {
    e.preventDefault();

    fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/users`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('token')}`
        },
        body: JSON.stringify({
            name: name,
            description: description,
            type: type,
            amount: amount
        })
    })
    .then(res => {
        return res.json()
    })
    .then(data => {
        if (data === true){
            Swal.fire({
                title: "Category added!",
                icon: "success",
            })
            Router.push('/category')
        } else {
            Router.push('/errors/1')
        }
    })
}

This is my routes:

router.post('/', auth.verify, (req, res) => {
    const user = auth.decode(req.headers.authorization)
    CategoryController.addCategory(req.body)
    .then(result => res.send(result))
})

This is my controllers:

module.exports.addCategory = (params) => {
    return User.findById(params.userId)
        .then((user, err) => {
            console.log(user)
            if(err) return false
            user.categories.push(params)
            return user.save()
                .then((updatedUser, err) => {
                    return err ? false : true
                })
                .catch(err => {
                    console.log(err)
                })
        })
        .catch(err => {
            console.log(err)
        })
}

This is the terminal error:

enter image description here

1 Answers

You are sending to backend object with: name, desc, type and amount, but not with userId property. And on backend your find call then returns null. Find is trying to fetch the user with undefined value.

Related