0

My desire is to update the products inside the shoppingCart[0]
The state: const [authenticatedUser, setAuthenticatedUser] = useContext<any>(UserContext)

console.log(authenticatedUser) displays the following: enter image description here

I've tried updating the value of the products array with the following code:
setAuthenticatedUser({ ...authenticatedUser, products: ['new item'] }) But it creates a new product array inside the authenticatedUser.

How can I update the products array inside authenticatedUser.shoppingCart[0].products ?

Data:

const [authenticatedUser, setAuthenticatedUser] = useState(
   {
    authenticated: true,
    id: "3i4jijrifjifrjifr",
    shoppingCart: [{
        createdAt: "2021-01-29T10:14:21.253Z",
        products: ['this is the array i want to update', '2', '3']
    }]
   }
)
1
  • you need to use useState, not useContext Commented Jan 29, 2021 at 13:49

3 Answers 3

1

try this:

setAuthenticatedUser({ ...authenticatedUser, shoppingCart:[{...authenticatedUser.shoppingCart[0],products:['newItem']}] })
Sign up to request clarification or add additional context in comments.

Comments

0
const authenticatedUserCopy = { ...authenticatedUser }
authenticatedUserCopy.shoppingCart[0].products = ['new product']
setAuthenticatedUser(authenticatedUserCopy)

Comments

0
{ 
    ...authenticatedUser,
    shoppingCart: authenticatedUser.shoppingCart.map(s => { //map all items
        return {
            ...s,
            products: [...s.products, 'new item'] //add item
        }
    })
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.