React.js Context API: How to only update a value pair of an object while maintaining other pairs?

Viewed 918

I am developing a web app using React and am using context API to store some information across multiple components of different hierarchy. I am storing an object that looks like below on App.js:

 /*
 import Userinfo from './context/Userinfo'
 */

 function App() {
      const [userinfo, setuserinfo] = useState({id: some_id, username: some_username, profile_picture: some_profile_picture})
 /*
 */
 }

and then use the context on a deeper component like below:

 import Userinfo from '../context/Userinfo';

 function Profile() {
      const {userinfo, setuserinfo)=useContext(Userinfo);

      const infoupdate = () => {  //Function to update the userinfo stored by context API
           setuserinfo({id: new_id, username: new_username, profile_picture: new_profile_picture})
      }
     /////////

The question is, how do I update only one pair of the stored object? For example, let's say I want to update only 'id' part while keeping the other fields same. What would be the syntax to do this?

Thanks a lot in advance!

2 Answers

To me this question is about useState() API instead of useContext().

The setState() function returned from const [state, setState] = useState(), in your example the setuserinfo() function, actually has another signature that takes in a function as argument.

When called, that function is passed in previous state as argument. You can simply spreed that prevState to preserve old pairs, and change only id field:

const infoupdate = () => {
    setuserinfo(prevState => ({
        ...prevState,
        id: new_id,
    }))
}

The idea is you make a copy of your object, and then change the field of the new object

const userinfo = {
  id: new_id, 
  username: new_username, 
  profile_picture: new_profile_picture
}

const newUserInfo = {
  ...userInfo, // deep copy userInfo into newUserInfo (
  id: 'new_id' // update id to 'new_id', other fields are not changed
}

// update userInfo 
setUserInfo(newUserInfo)

The way i created newUserInfo here is i combined the following lines into 1 liner

// create a copy of userInfo
const newUserInfo = {
  ...userInfo,
}

// change the id of the the new object
newUserInfo.id = 'new_id'
Related