<commit_before>import * as React from 'react';
import { useSelector } from 'react-redux';
import { useForm, Controller } from 'react-hook-form';
import { makeStyles } from '@material-ui/core/styles';
import { RootState } from 'js/store';
import { MemoCountryPicker } from './CountryPicker';
import { sectors, usage, topics } from './staticOptions';
import clsx from 'clsx';
import { Select, RadioGroup, FormControlLabel, Radio } from '@material-ui/core';
import 'css/formInputs.scss';
import 'css/editProfile.scss';

const userID = localStorage.getItem('userID');
const userToken = localStorage.getItem('userToken');
const profileURL = `https://production-api.globalforestwatch.org/user/${userID}`;

const EditProfile = (): JSX.Element => {
  const customColorTheme = useSelector(
    (store: RootState) => store.appSettings.customColorTheme
  );
  const [activeSector, setActiveSector] = React.useState(sectors[0].sector);
  const [activeSubsector, setActiveSubsector] = React.useState();
  const [activeUsage, setActiveUsage] = React.useState<string[]>([]);
  const [activeTopics, setActiveTopics] = React.useState<string[]>([]);
  const [activeCountry, setActiveCountry] = React.useState('');
  const [interestActiveCountry, setInterestActiveCountry] = React.useState('');
  const [existingProfileInfo, setExistingProfileInfo] = React.useState<any>({});
  const [originalSectorIndex, setOriginalSectorIndex] = React.useState<
    number | undefined
  >();
  const [updateSuccess, setUpdateSuccess] = React.useState(false);
  const [updateError, setUpdateError] = React.useState();
  const { register, handleSubmit, errors, control } = useForm();

  React.useEffect(() => {
    fetch(profileURL, {
      credentials: 'include',
      headers: {
        Authorization: `Bearer ${userToken}`
      }
    })
      .then(res => res.json())
      .then(data => {
        const profileData = data.data.attributes;
        if (profileData.fullName) {
          const name = profileData.fullName.split(' ');
          profileData.firstName = name[0];
          profileData.lastName = name[1];
        }
        if (data.data.attributes.sector) {
          const sectorIdx = sectors.findIndex(
            sector => sector.sector === data.data.attributes.sector
          );
          setOriginalSectorIndex(sectorIdx);
        }
        setExistingProfileInfo(data.data.attributes);
      })
      .catch(e => console.error(e));
  }, [updateSuccess]);

  const onDefaultSubmit = (data: any): void => {
    const payload = {
      ...data,
      aoiCountry: interestActiveCountry,
      country: activeCountry,
      sector: activeSector,
      interests: activeTopics,
      howDoYouUse: '',
      id: userID,
      loggedIn: true
    };

    //Get the subsectors
    if (
      data.hasOwnProperty('subsectorOther') &&
      data.subsectorOther.length !== 0
    ) {
      payload.subsector = payload.subsector + data.subsectorOther;
    }

    //Get the usage
    const activeUsagePayload = activeUsage.map(usage => {
      if (usage === 'Other' && data.usageOther !== 0) {
        return `${usage} ${data.usageOther}`;
      } else {
        return usage;
      }
    });
    payload.howDoYouUse = activeUsagePayload;

    //Update the API
    fetch(profileURL, {
      method: 'PATCH',
      headers: {
        Authorization: `Bearer ${userToken}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(payload)
    })
      .then(res => res.json())
      .then(msg => {
        if (msg?.errors) {
          setUpdateError(msg.errors[0].detail);
        } else {
          setUpdateSuccess(true);<commit_msg>elavating token info to the local state<commit_after>import * as React from 'react';
import { useSelector } from 'react-redux';
import { useForm, Controller } from 'react-hook-form';
import { makeStyles } from '@material-ui/core/styles';
import { RootState } from 'js/store';
import { MemoCountryPicker } from './CountryPicker';
import { sectors, usage, topics } from './staticOptions';
import clsx from 'clsx';
import { Select, RadioGroup, FormControlLabel, Radio } from '@material-ui/core';
import 'css/formInputs.scss';
import 'css/editProfile.scss';

const EditProfile = (): JSX.Element => {
  const customColorTheme = useSelector(
    (store: RootState) => store.appSettings.customColorTheme
  );
  const [activeSector, setActiveSector] = React.useState(sectors[0].sector);
  const [activeSubsector, setActiveSubsector] = React.useState();
  const [activeUsage, setActiveUsage] = React.useState<string[]>([]);
  const [activeTopics, setActiveTopics] = React.useState<string[]>([]);
  const [activeCountry, setActiveCountry] = React.useState('');
  const [interestActiveCountry, setInterestActiveCountry] = React.useState('');
  const [existingProfileInfo, setExistingProfileInfo] = React.useState<any>({});
  const [originalSectorIndex, setOriginalSectorIndex] = React.useState<
    number | undefined
  >();
  const [updateSuccess, setUpdateSuccess] = React.useState(false);
  const [updateError, setUpdateError] = React.useState();
  const [userInfo, setUserInfo] = React.useState<{
    userToken: null | string;
    userID: null | string;
    profileURL: null | string;
  }>({ userToken: null, userID: null, profileURL: null });
  const { register, handleSubmit, errors, control } = useForm();

  React.useEffect(() => {
    const userID = localStorage.getItem('userID');
    const userToken = localStorage.getItem('userToken');
    const profileURL = `https://production-api.globalforestwatch.org/user/${userID}`;
    fetch(profileURL, {
      credentials: 'include',
      headers: {
        Authorization: `Bearer ${userToken}`
      }
    })
      .then(res => res.json())
      .then(data => {
        const profileData = data.data.attributes;
        if (profileData.fullName) {
          const name = profileData.fullName.split(' ');
          profileData.firstName = name[0];
          profileData.lastName = name[1];
        }
        if (data.data.attributes.sector) {
          const sectorIdx = sectors.findIndex(
            sector => sector.sector === data.data.attributes.sector
          );
          setOriginalSectorIndex(sectorIdx);
        }
        setUserInfo({ userToken, userID, profileURL });
        setExistingProfileInfo(data.data.attributes);
      })
      .catch(e => console.error(e));
  }, [updateSuccess]);

  const onDefaultSubmit = (data: any): void => {
    const payload = {
      ...data,
      aoiCountry: interestActiveCountry,
      country: activeCountry,
      sector: activeSector,
      interests: activeTopics,
      howDoYouUse: '',
      id: userInfo.userID,
      loggedIn: true
    };

    //Get the subsectors
    if (
      data.hasOwnProperty('subsectorOther') &&
      data.subsectorOther.length !== 0
    ) {
      payload.subsector = payload.subsector + data.subsectorOther;
    }

    //Get the usage
    const activeUsagePayload = activeUsage.map(usage => {
      if (usage === 'Other' && data.usageOther !== 0) {
        return `${usage} ${data.usageOther}`;
      } else {
        return usage;
      }
    });
    payload.howDoYouUse = activeUsagePayload;

    //Update the API
    if (!userInfo.profileURL) return;
    fetch(userInfo.profileURL, {
      method: 'PATCH',
      headers: {
        Authorization: `Bearer ${userInfo.userToken}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(payload)
    })
      .then(res => res.json())
      .then(msg => {
        if (msg?.errors) {
          setUpdateError(msg.errors[0].detail);
        } else {
          setUpdateSuccess(true);
{'fraction_non_alphanumeric': 0.13957457983193278, 'fraction_numerical': 0.0015756302521008404, 'mean_word_length': 3.130694143167028, 'pattern_counts': {'":': 0, '<': 12, '<?xml version=': 0, '>': 34, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6015204', 'n_tokens_mistral': 2268, 'n_tokens_neox': 2246, 'n_words': 473}