How to update UserContext in functional components?

Viewed 82

I am building a MERN stack application and trying to figure out how to update my UserContext data.

The UserContext data is as follows:

{ jwt: "eyJhbGc..."
  user: {
    createdAt: "2022-05-05T10:52:22.653Z"
    currentChild: "abc789" <--- this is what I want to update
    email: "test@gmail.com"
    firstName: "lindsay"
    password: "$2b$10$CJjs9mvr8n4mTps1xxjmJe0jMK6Fo7Tg88qMXaHm5H6yFiOssq4Wa"
    updatedAt: "2022-06-01T11:25:42.450Z"
    __v: 0
    _id: "xyz123"
 }
}

UserContext.js:

import React, { createContext, useState } from 'react';

export const UserContext = createContext('');

export default ({ children }) => {
  const [user, setUser] = useState();
  return (
    <UserContext.Provider value={{ user, setUser }}>
      {children}
    </UserContext.Provider>
  );
};

index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import UserContextProvider from './context/UserContext';
import reportWebVitals from './reportWebVitals';

ReactDOM.render(
  <React.StrictMode>
    <UserContextProvider>
      <App />
    </UserContextProvider>
  </React.StrictMode>,
  document.getElementById('root')
);

reportWebVitals();

function where I want to update the currentChild value of user from UserContext:

const updateUserData = async (kid_id) => {
    
    const user_id = user.user._id; 
    let body = {
      kidID: kid_id,
    };
    try {
      const res = await fetch(`/api/users/update/${user_id}`, {
        method: 'PUT',
        headers: {
          'x-auth-token': user.jwt,
          'Content-type': 'application/json',
        },
        body: JSON.stringify(body),
      });
      const data = await res.json();    
      console.log('updateUserData', data);
      // ******************** update currentChild value of user here.. ************* 
      // how?? 
      return data;
    } catch (error) {
      setError(error.message);
    }
  };

Any help would be great. Everything so far I found via google is related to class components. Thanks

1 Answers

UPDATE I found a solution but feel free to add more feedback: in my update function I just grabbed the user data, updated the data like any other object and then used the setter function:

user.user.currentChild = data.currentChild;
 setUser(user);

I was thinking the solution would have been more complicated than that.

Related