简体   繁体   English

对 mongodb 进行更改时刷新用户数据

[英]refresh user data when changes are made to mongodb

I am new to react and MongoDB, I have this site where the user can log in and look at his detail like name…, coming from the db.我是新来的反应和 MongoDB,我有这个网站,用户可以登录并查看他的详细信息,如姓名……,来自数据库。 I am trying to find a way to update what is shown to the client when a change is made directly from the database, or when a button is clicked refresh user data, so it shows newly updated data from the database.我试图找到一种方法来更新直接从数据库进行更改时显示给客户端的内容,或者单击按钮刷新用户数据时,它会显示来自数据库的新更新数据。 I am using useReducer for authentication of the user and make updates to him from the client, but I can't find a way to update the data shown to the client.我正在使用 useReducer 对用户进行身份验证并从客户端对他进行更新,但我找不到更新显示给客户端的数据的方法。 If changes are made directly from the db, the user has to log out and log back in to see the updated version of them.如果直接从数据库进行更改,则用户必须注销并重新登录才能查看它们的更新版本。 Again, I am very new to useReducer and have only managed to barely make it work from what I could find, but I can't find this particular problem I have anywhere.再说一次,我对 useReducer 还是很陌生,而且我只能勉强让它从我能找到的东西中工作,但我在任何地方都找不到这个特殊的问题。 If someone could help, I greatly appreciate it.如果有人可以提供帮助,我将不胜感激。 Tell me if you need more context or any other file.如果您需要更多上下文或任何其他文件,请告诉我。

My AuthContext file with useReducer我的 AuthContext 文件与 useReducer

import React from "react";
import { createContext, useEffect, useReducer } from "react";

const INITIAL_STATE = {
  user: JSON.parse(localStorage.getItem("user")) || null,
  loading: false,
  error: null,
};

export const AuthContext = createContext(INITIAL_STATE);

const AuthReducer = (state, action) => {
  switch (action.type) {
    case "LOGIN_START":
      return {
        user: null,
        loading: true,
        error: null,
      };
    case "LOGIN_SUCCESS":
      return {
        user: action.payload,
        loading: false,
        error: null,
      };
    case "LOGIN_FAILURE":
      return {
        user: null,
        loading: false,
        error: action.payload,
      };
    case "LOGOUT":
      return {
        user: null,
        loading: false,
        error: null,
      };
    case "UPDATE_USER_DATE":
      const updatedUser = { ...state.user };
      updatedUser.activeUntil = action.payload;
      return {
        ...state,
        user: updatedUser,
      };
    case "UPDATE_USER":
      const updateUser = { ...state.user };
      return {
        ...state,
        user: updateUser,
      };
    default:
      return state;
  }
};

export const AuthContextProvider = ({ children }) => {
  const [state, dispatch] = useReducer(AuthReducer, INITIAL_STATE);

  useEffect(() => {
    localStorage.setItem("user", JSON.stringify(state.user));
  }, [state.user]);

  return (
    <AuthContext.Provider
      value={{
        user: state.user,
        loading: state.loading,
        error: state.error,
        dispatch,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
};

where i am trying to make the update happen我正在尝试进行更新的地方

import React, { useContext } from "react";
import { useState } from "react";
import useFetch from "../../hooks/useFetch";
import Footer from "../../components/OutFooter";
import Navbar from "../../components/OutNavbar";
import Sidebar from "../../components/OutSidebar";
import {
  ContractContainer,
  HeadingContainer,
  TypeH1,
  ActiveUntil,
  MonthlyWrapper,
  MonthlyContainer,
  MonthNumber,
  Price,
  Navbarback,
} from "./userinfoElements";
import { AuthContext } from "../../context/AuthContext";
import { Navigate } from "react-router-dom";
import moment from "moment";
import axios from "axios";

const Userinfo = () => {
  // for nav bars
  const [isOpen, setIsOpen] = useState(false);

  // set state to true if false
  const toggle = () => {
    setIsOpen(!isOpen);
  };

  const { user, dispatch } = useContext(AuthContext);
  if (!user) {
    return <Navigate to="/" />;
  }

  const { data } = useFetch(`/contracts/${user.contractType}`);

  let dateFormat = moment(user.activeUntil).format("DD/MMMM/yyyy");

  const update1Month = async () => {
    try {
      let newDate = moment(user.activeUntil).add(30, "days");
      dateFormat = newDate.format("DD/MMMM/yyyy");
      await axios.put(`/activedate/${user.namekey}`, {
        activeUntil: newDate,
      });
      dispatch({ type: "UPDATE_USER_DATE", payload: newDate });
    } catch (err) {
      console.log(err);
    }
  };



  const update3Month = async () => {
    try {
      let newDate = moment(user.activeUntil).add(90, "days");
      dateFormat = newDate.format("DD/MMMM/yyyy");
      await axios.put(`/activedate/${user.namekey}`, {
        activeUntil: newDate,
      });
      dispatch({ type: "UPDATE_USER_DATE", payload: newDate });
    } catch (err) {
      console.log(err);
    }
  };
  const update6Month = async () => {
    try {
      let newDate = moment(user.activeUntil).add(180, "days");
      dateFormat = newDate.format("DD/MMMM/yyyy");
      await axios.put(`/activedate/${user.namekey}`, {
        activeUntil: newDate,
      });
      dispatch({ type: "UPDATE_USER_DATE", payload: newDate });
    } catch (err) {
      console.log(err);
    }
  };
  const update12Month = async () => {
    try {
      let newDate = moment(user.activeUntil).add(365, "days");
      dateFormat = newDate.format("DD/MMMM/yyyy");
      await axios.put(`/activedate/${user.namekey}`, {
        activeUntil: newDate,
      });
      dispatch({ type: "UPDATE_USER_DATE", payload: newDate });
    } catch (err) {
      console.log(err);
    }
  };
  const refreshUser = async () => {
    try {
      dispatch({ type: "UPDATE_USER" });
    } catch (err) {
      console.log(err);
    }
  };
  return (
    <>
      <Sidebar isOpen={isOpen} toggle={toggle} />
      {/* navbar for smaller screens*/}
      <Navbar toggle={toggle} />
      <Navbarback /> {/* filling for transparent bacground navbar*/}
      <>
        <ContractContainer>
          <button onClick={refreshUser}>toooo</button>
          <TypeH1>
            Hello {user.fName} {user.lName}!
          </TypeH1>
          <HeadingContainer>
            <TypeH1>{data.contractType}</TypeH1>
            <ActiveUntil>Subscription active until {dateFormat}</ActiveUntil>
          </HeadingContainer>
          <MonthlyWrapper>
            <MonthlyContainer>
              <MonthNumber>1 Month</MonthNumber>
              <Price onClick={update1Month}>{data.month1Price}$</Price>
            </MonthlyContainer>
            <MonthlyContainer>
              <MonthNumber>3 Month</MonthNumber>
              <Price onClick={update3Month}>{data.month3Price}$</Price>
            </MonthlyContainer>
            <MonthlyContainer>
              <MonthNumber>6Month</MonthNumber>
              <Price onClick={update6Month}>{data.month6Price}$</Price>
            </MonthlyContainer>
            <MonthlyContainer>
              <MonthNumber>12Month</MonthNumber>
              <Price onClick={update12Month}>{data.month12Price}$</Price>
            </MonthlyContainer>
          </MonthlyWrapper>
        </ContractContainer>
      </>
      <Footer />
    </>
  );
};

export default Userinfo;

in particular ->特别是->

 const refreshUser = async () => {
    try {
      dispatch({ type: "UPDATE_USER" });
    } catch (err) {
      console.log(err);
    }
  }; 

I doubt you can cause a re-render by changing a document directly from the database.我怀疑您可以通过直接从数据库中更改文档来导致重新渲染。 However, if you want a refresh button, you can first create a new state不过如果想要刷新按钮,可以先新建一个state

const [refresh, setRefresh] = React.useState(false)

then pass this onClick handler to a refresh button which is in the same component as your user details stuff like然后将此 onClick 处理程序传递给刷新按钮,该按钮与您的用户详细信息位于同一组件中

<button onClick = {() => setRefresh(prev => !prev)}>Refresh</button>

After dabbling here and there, I resulted accidentally exactly what I needed.在这里和那里涉足之后,我意外地得到了我需要的东西。 I found that using useEffect I can load a function at the start of the page loading.我发现使用 useEffect 我可以在页面加载开始时加载 function 。 Accidentally doing this also resulted in updating my local stored user to the one in my database.不小心这样做也导致将我的本地存储用户更新为我数据库中的用户。 I changed some things in my context file and added a new controller on api side that posts already stored users.我在上下文文件中更改了一些内容,并在 api 一侧添加了一个新的 controller,该侧发布了已存储的用户。 If anyone requires further explanations or examples feel free to ask!如果有人需要进一步的解释或示例,请随时询问!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 服务数据变化时自动刷新导航栏 - Automatically refresh navbar when service data changes 如何更新Vue数据以反映用户输入对HTML所做的更改 - How to update Vue data to reflect changes in the HTML made by user input 如何在lobb.js中实现页面刷新(从服务器获取数据并丢失所做的所有更改)功能? - How to implement page refresh (fetch data from server and losing all changes made) functionality in backbone.js? ASP.NET 核心 - 当对 DB 进行某些更改时,使用 SignalR 刷新 UI - ASP.NET Core with - Refresh UI with SignalR when certain changes are made to the DB 当用户从 web 应用程序进行任何更改时,我如何通知本机应用程序进行更改 - How can i notify react native app for the changes, when any changes is made by user from web app 每秒检查一次json,并在数据更改时刷新页面 - check json every second and refresh page when data changes 当数据更改和查询不再满足时自动刷新网格 - Automatically refresh a grid when data changes and query is no longer satisfied 服务器上的数据更改时刷新客户端网页(php或javascript) - refresh client webpage when data changes on server (php or javascript) 使用用户进行的网站截图制作 - Making screenshot of the website with changes made by user 在用户的浏览器上缓存JavaScript和CSS,并在进行更改后加载新的JavaScript和CSS - Cache JavaScript & CSS on user's browser and load new one when changes are made
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM