dispatch updates only the first user on the database

Viewed 23

i have a website where some users are localystored and stored in my mongodb, i created some buttons where when clicked they will firstly call the current state of the user to be the same as the on in the db, then after it should update the date value of the current localystored user. Whenever the button to update the date is clicked, for every user that is logged in, only the first user registered in the database is changed. I think the problem is in the backed update call or the Authcontext file but cant find a way to fix it.

File where the change should happen when function updateXMonth is called

import React, { useContext, useEffect } from "react";

import { AuthContext } from "../../context/AuthContext";
import { Navigate } from "react-router-dom";
import useFetch from "../../hooks/useFetch";
import { useState } from "react";

import Footer from "../../components/OutFooter";
import Navbar from "../../components/OutNavbar";
import Sidebar from "../../components/OutSidebar";
import {
  ContractContainer,
  HeadingContainer,
  TypeH1,
  ActiveUntil,
  MonthlyWrapper,
  MonthlyContainer,
  MonthNumber,
  Navbarback,
  Desc,
  TypeH2,
  Subtitle,
} from "./userinfoElements";

import moment from "moment";
import axios from "axios";
import { Button } from "../../components/ButtonElements";

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);
  const { data } = useFetch(`/contracts/${user?.contractType}`);
  // useEffect(() => {
  //   if (user) {
  //     userUpdate();
  //   }
  // });

  let userUpdate = async () => {
    try {
      let res = await axios.post(`/auth/${user?.namekey}`);
      dispatch({ type: "LOGIN_SUCCESS", payload: res.data.details });
      let date = new Date().toJSON();
      if (res.data.details.activeUntil < date) {
        dispatch({ type: "CONTRACT_EXPIRED" });
        console.log("Users contract has expired");
      }
    } catch (err) {
      console.log(err);
    }
  };

  if (!user) {
    return <Navigate to="/" />;
  }
  let dateFormat = moment(user.activeUntil).format("DD/MMMM/yyyy");

  const update1Month = async () => {
    try {
      let res = await axios.post(`/auth/${user.namekey}`);
      dispatch({ type: "LOGIN_SUCCESS", payload: res.data.details });
      let newDate = moment(res.data.details.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 res = await axios.post(`/auth/${user?.namekey}`);
      dispatch({ type: "LOGIN_SUCCESS", payload: res.data.details });
      let newDate = moment(res.data.details.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 res = await axios.post(`/auth/${user?.namekey}`);
      dispatch({ type: "LOGIN_SUCCESS", payload: res.data.details });
      let newDate = moment(res.data.details.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 res = await axios.post(`/auth/${user?.namekey}`);
      dispatch({ type: "LOGIN_SUCCESS", payload: res.data.details });
      let newDate = moment(res.data.details.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);
    }
  };

  return (
    <>
      <Sidebar isOpen={isOpen} toggle={toggle} />
      {/* navbar for smaller screens*/}
      <Navbar toggle={toggle} />
      <Navbarback /> {/* filling for transparent bacground navbar*/}
      <>
        <ContractContainer>
          <TypeH1>
            Hello {user.fName} {user.lName}!
          </TypeH1>
          <HeadingContainer>
            <TypeH2>
              Your contract type:{" "}
              <span style={{ color: "red" }}>{data.contractType}</span>
            </TypeH2>
            <ActiveUntil>
              Subscription active until{" "}
              <span style={{ color: "red" }}>{dateFormat}</span>
            </ActiveUntil>
          </HeadingContainer>
          <Subtitle>
            Pay right now and get imediate access. The more the cheaper. If you
            have a subscription already active, no days will be lost during the
            proccess, they will only be added.
          </Subtitle>
          <MonthlyWrapper>
            <MonthlyContainer>
              <MonthNumber>1 Month</MonthNumber>
              <Button onClick={update1Month}>{data.month1Price}$</Button>
              <Desc>Pay right now to add 1 month to your subscription.</Desc>
            </MonthlyContainer>
            <MonthlyContainer>
              <MonthNumber>3 Months</MonthNumber>
              <Button onClick={update3Month}>{data.month3Price}$</Button>
              <Desc>Pay right now to add 3 months to your subscription.</Desc>
            </MonthlyContainer>
            <MonthlyContainer>
              <MonthNumber>6 Months</MonthNumber>
              <Button onClick={update6Month}>{data.month6Price}$</Button>
              <Desc>Pay right now to add 6 months to your subscription.</Desc>
            </MonthlyContainer>
            <MonthlyContainer>
              <MonthNumber>12 Months</MonthNumber>
              <Button onClick={update12Month}>{data.month12Price}$</Button>
              <Desc>Pay right now to add 12 months to your subscription.</Desc>
            </MonthlyContainer>
          </MonthlyWrapper>
        </ContractContainer>
      </>
      <Footer />
    </>
  );
};

export default Userinfo;

controller file for /activedate/

import User from "../models/User.js";

export const updateActiveDate = async (req, res, next) => {
  try {
    await User.updateOne({
      $set: { activeUntil: req.body.activeUntil },
    });

    res.status(200).json("Active date has been updated.");
  } catch (err) {
    next(err);
  }
};

AuthContext file

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

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

export const AuthContext = createContext(INITIAL_STATE);

const AuthReducer = (state, action) => {
  switch (action.type) {
    case "LOGIN_START":
      return {
        user: null,
        loading: true,
        error: null,
        expired: false,
      };
    case "LOGIN_SUCCESS":
      return {
        user: action.payload,
        loading: false,
        error: null,
        expired: false,
      };
    case "CONTRACT_EXPIRED":
      return {
        user: null,
        loading: false,
        error: null,
        expired: true,
      };

    case "LOGOUT":
      return {
        user: null,
        loading: false,
        error: null,
        expired: false,
      };
    case "LOGIN_FAILURE":
      return {
        user: null,
        loading: false,
        error: action.payload,
        expired: false,
      };
    case "UPDATE_USER_DATE":
      const updatedUser = { ...state.user };
      updatedUser.activeUntil = action.payload;
      return {
        ...state,
        user: updatedUser,
      };

    default:
      return state;
  }
};

export const AuthContextProvider = ({ children }) => {
  const [state, dispatch] = useReducer(AuthReducer, INITIAL_STATE);
  //update LStorage when user state updates
  useEffect(() => {
    localStorage.setItem("user", JSON.stringify(state.user));
  }, [state.user]);

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

0 Answers
Related