0

I send data to another file with this:

import TropheeNameBlock from "../media-components/trophee-name-block"
<TropheeNameBlock currentUser={currentUser} userGender={userGender} />

I receive data from another file on the variable currentUser and userGender

I use a switch case to display an icon. I have put a console.log(currentUser) the variable currentUser contain a Json like this:

{
"id":"4a1d-aeeb-a54ede02e90c",
"firstName":"MyFirstname",
"lastName":"MyLastname",
"gender":0,
"birthDate":"2021-08-05T15:43:00+02:00",
"phone":"000000",
"email":"myemail@mail.com",
"optin":true,
"language":"en-EN",
"country":"EN",
"streetName":"myStreetName",
"houseNumber":"",
"houseNumberExt":null,
"postalCode":"",
"city":"",
"idlsm":null,
"cars":[
"/cars/3854f416b36c",
"/cars/901cf0124e39"
],
"status":1,
"countOfUserReward":0,
"countOfEmailToRead":1,
"subscriptionDate":"2021-08-05T15:43:00+02:00",
"deletionDate":null,
"validationDate":"2021-08-05T17:15:55+02:00",
"lastUpdateDate":null,
"newPasswordRequestAt":"2021-08-05T17:15:55+02:00",
"newPasswordRequestToken":"TOKEN",
"events":[
"/car_events/b1ae-dbc2558f83c0",
"/car_events/802a-0d869bb7422d"
],
"carRemoveHistories":[
],
"rewards":[
],
"dealer":"4682-9223-df3cf582a883",
"particleName":"",
"reminderChannelNotification":false,
"reminderChannelSMS":false,
"reminderChannelEmail":true,
"offerChannelNotification":false,
"offerChannelSMS":true,
"offerChannelEmail":false,
"welcomeTimeline":true,
"welcomeRewards":true,
"contacts":[
],
"nissanCards":[
],
"source":"dealer_platform",
"medium":null,
"campaign":null,
"boardingFinishDate":null,
"rewardsAccessEndDate":null,
"scheduledDeletionDate":null,
"exportedToLsm":false,
"oldDealer":0,
"onboardedBy":"Onboarder",
"licencePlate":"ABC123"
}

My code with the switch case is like this:

import React from "react"
import {useTranslation} from 'react-i18next';

const TropheeNameBlock = ({currentUser, userGender}) => {
  const {t} = useTranslation();
  return(
    <>
      {(() => {
        switch (currentUser.status) {
          case 1:
            return (<span className="icon-win icon-win-text"><span className="path1"></span><span className="path2"></span><span className="path3"></span><span className="text">{t('generic.status_level.' + currentUser.status)}</span></span>);
          case 2:
            return (<span className="icon-win icon-win-text silver"><span className="path1"></span><span className="path2"></span><span className="path3"></span><span className="text">{t('generic.status_level.' + currentUser.status)}</span></span>);
          case 3:
            return (<span className="icon-win icon-win-text gold"><span className="path1"></span><span className="path2"></span><span className="path3"></span><span className="text">{t('generic.status_level.' + currentUser.status)}</span></span>);
          case 4:
            return (<span className="icon-win icon-win-text platinum"><span className="path1"></span><span className="path2"></span><span className="path3"></span><span className="text">{t('generic.status_level.' + currentUser.status)}</span></span>);
        }
      })()}

      <h3 className="pt-3 mb-2">{userGender} {currentUser.lastName}</h3>
    </>
  )
}

export default TropheeNameBlock

In my Json I would like to access in my field status. In this case when I do a currentUser.status the variable are empty. I have try to use a console.log(currentUser.status) inside the switch case like this:

switch (currentUser.status) {
              case 1:
                console.log(currentUser.status);
                return (<span className="icon-win icon-win-text"><span className="path1"></span><span className="path2"></span><span className="path3"></span><span className="text">{t('generic.status_level.' + currentUser.status)}</span></span>);

But the console log is not display on the console because I think it don't enter to the switch case.

The main file:

The call API to get currentUser:

useEffect(() => {
    UserService.getMeUserId({
      "id": user.id,
      "token": localStorage.getItem('token')
  }).then( (resUser) => {
    localStorage.setItem('currentUser', JSON.stringify(resUser.data.user));
    setCurrentUser(localStorage.getItem('currentUser'));
  })

)}

Here the code where I call the file TropheeNameBlock

const content = () => {
    return(
      <div class="row p-4">
        <div class='col-md-12'>
            <div class='p-2'>
                <a href="/customerboard" className="button white back align-self-center">{t('Back to client list')}</a>
            </div>
        </div>
        <div className="col-lg-4 d-none d-lg-block p-4 without-arrow">
          <div className="status-container status-bronze white-container py-3 px-3 mb-3">
            <TropheeNameBlock currentUser={currentUser} userGender={userGender} />
            <hr />
            <h3 className="mb-2">{t('my_profil.rewards_history')}</h3>
            <RewardBlock currentUser={currentUser} />
          </div>
          <h3 className="text-uppercase">{t('my_profil.my_dealer.title')}</h3>
          <div className="white-container py-2 px-3 mb-3">
            <ul className="list-link-picto">
                <li className="mb-0 py-3 w-100"><a to="/profile/my-dealer" state={{id: currentDealer.id}} className="my-dealer"><span className="icon-dealer-favorite icon"></span><h3 className="mb-0">{currentDealer.name}</h3></a></li>
            </ul>
          </div>
          <h3 className="text-uppercase">{t('my_profil.my_vehicles')}</h3>
          <div className="white-container py-0 px-3 mb-3">
          <ul className="list-link-picto">
              { getCarsMedia()}
          </ul>
          </div>
      </div>
      <div class="col-lg-8 p-4">
        <div className="white-container">
          <h1 className="text-uppercase with-border-top with-border-bottom fs-20">{t('timeline.title')}</h1>
          <p>{t('timeline.description')}</p>
          <div className="d-flex align-items-center justify-content-between">
            {getCars()}
          </div>
          <hr className="mt-2" />
          {getEvents()}
        </div>
      </div>
    </div>
    )
  };

  let userGender = '';
  if(currentUser) {
    userGender = t('generic.forms.form_options.user_title.'+ currentUser.gender);
  }
  
    return(
      <div className="wrapper">
        <div className="container">
          <main>
            <header className="header py-2">
                <div className="container d-flex align-items-center">
                    <img src={logoNissanNow} alt="Nissan Now" width="160" className="mr-auto"/>
                    <span className="dark-red cursor-pointer" onClick={() => logout()}><span
                        className="icon-logout-2 icon align-middle"></span>{t('Logout')}</span>
                </div>
            </header>
              <BodyClass name="large-wrapper" />
                {content()}
          </main>
          <footer className="d-flex justify-content-around d-md-block text-center footer">
            {/* <Link to="#" className="mx-md-4" onClick={(e) => toggleModale(e)}>{intl.formatMessage({id: "footer.terms"})}</Link> */}
          </footer>
        </div>
      </div>
    )
};

Do you know why the data on currentUser are lost inside the switch case ?

Thanks you

  • Maybe this can help you, https://stackoverflow.com/a/46593006/5955138 – rcanpahali Aug 13 '21 at 07:51
  • Please show `console.log(currentUser)` before `return ` – Viet Aug 13 '21 at 07:53
  • @Viet it's the same result as my json on my post –  Aug 13 '21 at 11:44
  • Your code is working for me nicely. – zx01 Aug 16 '21 at 09:08
  • I think too but when I display my page the console log is undefined currentUser –  Aug 16 '21 at 09:10
  • The error is somewhere else maybe. Maybe you are not sending the correct values of `currentUser` and `userGender`. Also, add a `default` case in switch or else it will give you warnings. – zx01 Aug 16 '21 at 09:12
  • I think it's because the page TropheeNameBlock loading before my first page and the data are empty. I don't know why the data load before the main page. –  Aug 16 '21 at 09:13
  • Could you please add the code where you are fetching the values of those two? – zx01 Aug 16 '21 at 09:15
  • @zx01 I have add more informations –  Aug 16 '21 at 09:21

1 Answers1

0

I have found the solution.

I needed to use Json.Parse because I have stringify my data before

setCurrentUser(JSON.parse(localStorage.getItem('currentUser')));